more skeleton program Flashcards
(14 cards)
How does the program handle invalid user input, and what happens to the game state when the user enters an invalid expression?
If the input is invalid, CheckIfUserInputValid() returns False, and the program deducts a point from the score.
- targetlist and numbers allowed remain unchanged
How does the program manage the Targets list throughout the game, and what is the significance of updating and removing targets from the list?
- The Targets list represents the goals the player needs to achieve. Each time a target is hit, it is removed by setting it to -1
- Updating the target list allows new targets to be added, while previously hit targets are marked as completed
- This ensures that the player has new targets to reach as they progress through the game
What is the role of the NumbersAllowed list, and how is it updated throughout the game? What happens if a user tries to use a number not in the allowed list?
- NumbersAllowed list represents the numbers that the user can use to form valid expressions.
- Whenever a user uses a number from this list in a valid expression, that number is removed from NumbersAllowed for the next round.
- If a user tries to use a number that is not in NumbersAllowed, the program will reject the input
Explain the process that occurs when the game is over. How is the final score displayed, and what condition causes the game to end?
- The game ends when all the targets are completed, which is indicated by the first target being set to -1.
- When this condition is met, GameOver is set to True, and the game loop terminates. The final score is then displayed using the DisplayScore() function.
\d+
\s*
what do these do
/d+ - Matches one or more digits (numbers).
- \s* → Matches zero or more spaces (this allows spaces but doesn’t require them).
what does “r” before a string do eg:|re.search(r”^(\d+\s[+-*/]\s)+\d+$”, UserInput)
With a raw string, Python treats backslashes as normal characters, so we don’t need to double them.
- without them, we would have to write
re.search(“^(\d+\s[\+\-\/]\s*)+\d+$”, UserInput)
Brackets question flow
Numbers → output queue
( → push on stack
) → pop until (
Operator → pop operators with higher precedence, then push
End → pop all remaining operators
ConvertToRPNWithBrackets uses a stack to handle operators and parentheses by precedence. Numbers go straight to output. ( pushes on stack, ) pops until (. Operators pop from stack if they have higher precedence than incoming operator. Finally, all operators popped to output.
What regex pattern is used to validate the user input allowing brackets?
r”[0-9+-*/()]+”
brackets question: how to grab multi-digit numbers (\d+) or any single operator/bracket
tokens = re.findall(r’\d+|[()+-*/]’, UserInput)
ConvertToRPNWithBrackets ccode modification
for token in tokens:
if token.isdigit():
# If token is a number, check it is within allowed max number
if 0 <= int(token) <= MaxNumber:
# Valid number: add to RPN output queue directly
RPNQueue.append(token)
else:
# If invalid number, you could handle error here or ignore (skipping in this code)
pass
elif token == '(': **# Left bracket always pushed to operator stack Operators.append(token)** elif token == ')': **# On encountering right bracket: # Pop operators from stack to RPN queue until we find a left bracket** while Operators and Operators[-1] != '(': RPNQueue.append(Operators.pop()) **# Remove the left bracket '(' from stack (don't add to output)** if Operators and Operators[-1] == '(': Operators.pop() else: ** # Token is an operator (+, -, *, /) # While there are operators on stack with higher or equal precedence (and not '('), # pop them to the RPN queue before pushing current operator** while (Operators and Operators[-1] != '(' and Precedence.get(Operators[-1], 0) >= Precedence[token]): RPNQueue.append(Operators.pop()) **# Push the current operator onto the stack Operators.append(token) # After processing all tokens, pop any remaining operators from stack to RPN queue** while Operators: RPNQueue.append(Operators.pop()) **# Return the final RPN expression as a list of tokens** return RPNQueue ## end change
brackets question : checkvalidoperator function
CHANGE
def CheckValidOperator(Item):
# Returns True if Item is one of the valid operators or brackets
return re.search(r”[+-*\/()]”, Item) is not None
#END CHANGE
brackets question: updated checkifuserinputvalid function
change
def CheckIfUserInputValid(UserInput):
return re.fullmatch(r”[0-9+-*/()]+”, UserInput) is not None
## end change
hint q using brute force (and using more than 2 numbers)
START CHANGE
def display_hint(Targets,NumbersAllowed):
Operators = list(‘+/-*’)
NumberOfHints = 5
Loop = 1000
while Loop > 0 and NumberOfHints > 0:
Loop -= 1
TempNumbersAllowed = NumbersAllowed.copy()
random.shuffle(TempNumbersAllowed)
Guess = str(TempNumbersAllowed[0]) for i in range(1, random.randint(1,4)+ 1): Guess += Operators[random.randint(0,3)] Guess += str(TempNumbersAllowed[i]) EvaluatedAnswer = EvaluateRPN(ConvertToRPN(Guess)) if EvaluatedAnswer != -1 and EvaluatedAnswer in Targets: print('hint:' + Guess) NumberOfHints -= 1 if Loop <= 0 and NumberOfHints == 5: print('i couldnt find a hint')
END CHANGE
allow user to save
def SaveGameToFile(Targets, NumbersAllowed, Score):
try:
with open(“savegame.txt”,”w”) as f:
f.write(“ “.join(map(str, Targets)))
f.write(“\n”)
f.write(“ “.join(map(str, NumbersAllowed)))
f.write(“\n”)
f.write(str(Score))
f.write(“\n”)
print(“____Game saved____”)
print()
except:
print(“Failed to save the game”)
def LoadGameFromFile(): try: with open("savegame.txt","r") as f: Targets = list(map(int, f.readline().split())) NumbersAllowed = list(map(int, f.readline().split())) Score = int(f.readline()) print("\_\_\_\_Game loaded\_\_\_\_") print() except: print("Failed to load the game") print() return [],[],-1 return Targets, NumbersAllowed, Score