skeleton program notes Flashcards

You may prefer our related Brainscape-certified flashcards:
1
Q

in the displayscore() function, why is the score converted into a string

A

to allow string concatenation (string + string) because string+integer will give u an error

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

why is it necessary to validate the user input in CheckIfUserInputValid() function

A
  • ensures that only formatted mathematical expressions are processed
  • without validation, the program might try to parse invalid inputs
  • this may raise runtime errors such as syntax errors
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

what does end=“” do

A

ensure that the output from the print() function doesn’t move to a new line after each fall
- instead, everything printed remains on the same line

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

what does the CheckValidNumber() function do

A

is responsible for validating whether a number (in string form) is a valid number to be used in the game, based on certain criteria

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

how the CheckValidNumber() function works

A
  1. Regex Check:
    - uses the re.search() function to check if the Item string consists of only digits (^[0-9]+$). This regular expression ensures that the string only contains numeric characters. If it matches, the function proceeds; otherwise, it returns False.
  2. Convert to Integer:
    After confirming that Item is a valid number (made up of digits only), the function converts Item to an integer using int(Item) and stores it in ItemAsInteger.

Range Check:
- The function then checks if the integer is within a valid range (i.e., greater than 0 and less than or equal to MaxNumber). If so, it returns True, indicating that the number is valid.
If any of these checks fail, the function returns False, indicating that the number is not valid.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

what is the purpose of the RemoveNumbersUsed() function

A

The RemoveNumbersUsed() function is responsible for updating the list of available numbers (NumbersAllowed) after the user has used some of the numbers in a mathematical expression.
- This function ensures that once a number has been used, it is removed from the list and cannot be used again until the list is refreshed

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

step by step analysis of how RemoveNumbersUsed() works

A

Convert User Input to Reverse Polish Notation (RPN):
The function begins by calling ConvertToRPN() on the UserInput. This converts the mathematical expression into RPN format, which is easier to evaluate programmatically.

Iterate Through the RPN Expression:
- The function then loops through each item in the RPN expression (UserInputInRPN), which is a list of operands and operators.

Check if the Item is a Valid Number:
- Inside the loop, CheckValidNumber() is used to verify whether the item in the RPN expression is a valid number within the allowed range (i.e., it should be a number and fall within MaxNumber).

Remove Used Numbers:
- If the item is a valid number, it checks if that number exists in the NumbersAllowed list. If it does, it removes the number from the list, indicating that the number has been used.

Return the Updated List:
- Once all valid numbers used in the expression have been removed, the function returns the updated list of available numbers

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Function: CheckNumbersUsedAreAllInNumbersAllowed() purpose

A
  • is responsible for checking whether the numbers in the user input expression (converted into Reverse Polish Notation) are valid.
  • Specifically, it ensures that the numbers used in the expression are all available in the NumbersAllowed list, which is crucial for game integrity.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Function: CheckNumbersUsedAreAllInNumbersAllowed() how it works

A

takes two inputs:
- NumbersAllowed: A list of numbers that the user can use in their calculations.
- UserInputInRPN: A list of operands and operators in Reverse Polish Notation (RPN).

  • The function checks if every number in the UserInputInRPN list (which is a converted version of the user’s mathematical input) is in the NumbersAllowed list. If all numbers are valid, it returns True; if any number is invalid, it returns False.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Function: CheckNumbersUsedAreAllInNumbersAllowed() annotations

A

Create Temporary List (Temp):
- We first create a copy of the NumbersAllowed list by iterating over it and appending each item to the Temp list.
- This is done to avoid modifying NumbersAllowed directly while iterating.

Loop through UserInputInRPN:
- The UserInputInRPN list contains all the operands (numbers) and operators from the user’s input expression (after converting it to RPN). We loop through this list to check each item.

Check if the Item is Valid:
- CheckValidNumber(Item, MaxNumber) checks if the item is a valid number.
- This ensures the user input consists only of valid, allowed numbers. The validation checks if the number is within the acceptable range (from 1 to MaxNumber).

Check if the Item Exists in Temp:
- If the number is valid, we then check if the number exists in Temp. If it does, we remove it from Temp, ensuring that each number can only be used once.

Return True or False:
- If any number is not found in Temp, we return False, indicating that the user has attempted to use an invalid number (i.e., a number not allowed or already used).
If we finish checking all the items without finding an invalid one, we return True.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What would happen if the numbers in UserInputInRPN are not removed from Temp after being used?

  • CheckNumbersUsedAreAllInNumbersAllowed()
A

If the numbers are not removed from Temp, the function would still consider them available for subsequent uses, meaning the user could reuse the same number multiple times even if they have already used it. This could lead to an invalid game state.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

CheckIfUserInputEvaluationIsATarget Function() purpose

A

checks whether the evaluated user input matches any of the target numbers in the game.
- If the input matches a target, score’s updated and target from the list is removed - rewards the user with points if they get it right.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

CheckIfUserInputEvaluationIsATarget Function() how it works

A
  1. use the EvaluateRPN function to evaluate the user’s input, which has already been converted into (RPN). This will return the result of the mathematical expression.
    - If the expression is invalid (for example, division by zero or an empty input), EvaluateRPN returns -1.
  2. Check for a Valid Evaluation: If the result of the user’s expression (UserInputEvaluation) is not -1, the function proceeds to check whether the evaluation matches any of the targets.
  3. Loop Through Targets: The function loops through the list of targets. If any target matches the result of the user input evaluation, it
    - Adds 2 points to the user’s score.
    - Sets that target to -1 to indicate it’s been “used” or “hit”.
    - Sets a flag (UserInputEvaluationIsATarget) to True to indicate the user hit a target.
  4. Return Values: The function returns two values:
    - UserInputEvaluationIsATarget: A boolean indicating whether the user hit a target.
    - Score: The updated score, including the points for hitting a target.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

for Count in range(0, len(Targets)): what does this mean

A
  • iterates using the index (Count) of each element in the list.
  • eg if the target list has 10 elements, the iteration would be Target[0] , Target[1], Target[2] ,….Target[9] , (10 not included)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Why is the variable UserInputEvaluationIsATarget necessary?

A

to indicate if the user hit a target. (set to True is this happens)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What does EvaluateRPN(UserInputInRPN) do?

A

Evaluates the user’s input expression in Reverse Polish Notation (RPN) format. This converts the user input (parsed into RPN) into its numerical result (a single number or -1 for invalid inputs).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

why do we use the CoonvertToRPN function

A

because RPN is easier to evaluate programmatically compared to infix notation.

18
Q

in the evaluateRPN() function, why is pop(0) used in this :

while UserInputInRPN[0] not in [”+”, “-“, “*”, “/”]:
S.append(UserInputInRPN[0])
UserInputInRPN.pop(0)

A

pop(0) removes and returns the element at index 0 (the first element) from the list. This allows us to move through the list sequentially from the beginning. After pushing the operand to the stack, we remove it from the input list to keep processing the remaining items.

19
Q

Once an operator is encountered, the following steps occur, in evaluateRPN()

A

Pop Two Operands from the Stack:

The operator’s operands are the last two numbers that were pushed onto the stack. We first pop the second operand (Num2), and then pop the first operand (Num1).
S[-1] gives the last item of the stack (the most recently pushed operand), and S.pop() removes that item from the stack.

Perform the Calculation:
- The operator at UserInputInRPN[0] determines which arithmetic operation will be performed. Based on whether the operator is +, -, *, or /, the corresponding operation is executed, and the result is stored in Result.

20
Q

Remove the Operator from UserInputInRPN and Push Result - evaluateRPN()

A

UserInputInRPN.pop(0)
S.append(str(Result))

  • After performing the operation, we remove the operator (UserInputInRPN[0]) from the front of the list using pop(0).
  • We then push the result of the operation (Result) back onto the stack as a string using S.append(str(Result)).
  • This step ensures that the result of the current operation becomes part of the stack, and it may be used in subsequent operations.
21
Q

if float(S[0]) - math.floor(float(S[0])) == 0.0:
return math.floor(float(S[0]))
else:
return -1

A
  • At the end of the loop, S should contain exactly one element: the final result of the entire expression. The function checks if this result is an integer or a floating point number:

Check if the result is an integer:
- If the result is an integer, float(S[0]) - math.floor(float(S[0])) == 0.0 will be True.
- In this case, it returns the integer value of the result using math.floor(float(S[0])).

Handle non-integer results:
- If the result is not an integer (i.e., a floating-point number with decimals), the function returns -1, indicating that there was an issue with the input or result (such as an incorrect calculation or invalid RPN expression).

22
Q

Function: GetNumberFromUserInput purpose

A
  • designed to extract a number from a string, based on the current position in the string.
  • It handles the extraction of numeric values that are part of a mathematical expression (specifically in the context of RPN), considering the possibility of multi-digit numbers.
23
Q

Function: GetNumberFromUserInput code walkthrough

A

Initialize Variables:
- Number: This will store the number we extract from the input string.
- MoreDigits: A flag to keep track of whether there are more digits to process in the string.

While Loop:
- This loop will run as long as there are more digits to extract (MoreDigits is True).
- The condition checks whether the current character (UserInput[Position]) is a digit using a regular expression ([0-9]).
re.search(“[0-9]”, str(UserInput[Position])) is None checks if the character is not a number.
- If the character is a number, it’s added to the Number string.

Move to the Next Character:
- The position is incremented (Position += 1), and the loop continues until we encounter a non-digit or the end of the string.

Exit the Loop:
- The loop will stop once it encounters a non-digit or reaches the end of the string.

Return Values:
- If a number was found (Number is not an empty string), the function returns the extracted number as an integer and the new position after the number.
- If no valid number was found, the function returns -1 and the current position.

24
Q

Explanation and Why It Works: GetNumberFromUserInput

A

Extracting Multi-Digit Numbers:
- The function handles multi-digit numbers by continuously appending characters (digits) to the Number variable. For example, in the input “123+456”, the function will extract 123 first and then 456 after the +.

Regex Check:
- The function uses re.search(“[0-9]”, str(UserInput[Position])) to ensure that only numeric digits are considered valid characters for a number. If the current character isn’t a digit, it stops appending to Number and moves to the next part of the string.

25
Q

how the UpdateTarget function works in depth

A

Loop through the targets: - The loop runs from the start of the target list up until the second-to-last item.

Each target in the list is shifted to the left.
- This ensures that the first target is removed, and a new target is added at the end of the list.
pop method:
- The pop() function is used to remove the last item in the list. This simulates the idea of getting rid of an old target that is no longer relevant.

Training mode vs. normal game mode:
- In Training mode, the last target is duplicated at the end of the list. This is done to practice the same target again.
- In normal game mode, a new random target is added to the list using the GetTarget(MaxTarget) function.

26
Q

purpose of updatetargets

A
  • The function serves to rotate the targets in the game, ensuring that old targets are removed and new ones are added to keep the game progressing.
  • The distinction between training and normal game modes alters how the targets are updated after each round.
27
Q

DisplayState

A

In-Depth Explanation:

The DisplayState function calls other functions to show the game state:
- DisplayTargets(Targets): Shows the list of targets. DisplayNumbersAllowed(NumbersAllowed): Displays the numbers the player is allowed to use in the current round.
- DisplayScore(Score): Shows the current score of the player.
Purpose:
- The function consolidates the display process by calling three different functions to update the screen. This makes the main game loop more organized by separating concerns between the display of different game aspects.

28
Q

DisplayTargets()

A

Loop through the targets:
- For each target in the list:
If the target is -1 (meaning the target has been hit), it displays an empty space.
- If the target is a number, it prints the target number.

Formatting:
- The | symbols are used to create a border around each target to make them more visually distinct on the screen.

Purpose:
The DisplayTargets function displays the list of targets, showing which targets have been hit (-1) and which are still active

29
Q

FillNumbers()

A

Training mode:
- If the game is in training mode, it returns a predefined set of numbers ([2, 3, 2, 8, 512]). This makes it easier to practice with a fixed set of numbers.

Normal game mode:
- In normal mode, the function adds random numbers to the list of NumbersAllowed until there are 5 numbers in total. It uses the GetNumber(MaxNumber) function to generate random numbers up to the MaxNumber limit.

Purpose:
- The function initializes the available numbers that the player can use. In training mode, these numbers are fixed, while in normal mode, they are randomly generated.

30
Q

CreateTargets()

A

In-Depth Explanation:
Initial empty targets: The first 5 targets are set to -1 (indicating that they are not yet hit and are initially empty).

Adding random targets: The function then adds random targets using the GetTarget(MaxTarget) function. The number of targets is determined by the SizeOfTargets parameter.

Purpose:
The function creates the list of targets for the game. It starts with a few empty targets (-1) and then fills the rest with randomly generated target values.

31
Q

What is the primary purpose of the PlayGame function?

A

To manage the gameplay loop, validate user input, evaluate targets, and update the game state.

32
Q

What does the DisplayState function do in the PlayGame function?

A

It shows the current state of the game, including targets, allowed numbers, and the score.

33
Q

Why is user input converted to Reverse Polish Notation (RPN) in the PlayGame function?

A

To simplify the evaluation of the mathematical expression entered by the user.

34
Q

What happens if the user’s input contains numbers not in NumbersAllowed?

A

The input is deemed invalid, and the score is reduced by 1.

35
Q

Which function checks if the user’s RPN evaluation matches any target

A

CheckIfUserInputEvaluationIsATarget

36
Q

How does PlayGame handle hitting a target successfully?

A

It adds points to the score, marks the target as hit, removes used numbers, and refills the allowed numbers.

37
Q

What condition ends the game in the PlayGame function?

A

The game ends when Targets[0] is not equal to -1, indicating that a target remains unmet.

38
Q

What is the significance of Score -= 1 in the PlayGame function?

A

It ensures that players are penalized for incorrect or invalid inputs

39
Q

What does the Choice variable represent in the Main function?

A

It stores the user’s input to decide if they want to play the training game or a random game.

40
Q

What function is called to generate random targets when the user does not select the training game?

A

The CreateTargets function is called to generate random targets based on MaxNumberOfTargets and MaxTarget

41
Q

What does the FillNumbers function do in the Main function?

A

It populates the NumbersAllowed list with numbers based on whether it’s the training game or a random game.