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?
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?
Explain the process that occurs when the game is over. How is the final score displayed, and what condition causes the game to end?
\d+
\s*
what do these do
/d+ - Matches one or more digits (numbers).
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 0 <= int(token) <= MaxNumber:
RPNQueue.append(token)
else:
pass
elif token == '(':
Operators.append(token)**
elif token == ')':
**# On encountering right bracket:
while Operators and Operators[-1] != '(':
RPNQueue.append(Operators.pop())
if Operators and Operators[-1] == '(':
Operators.pop()
else:
while (Operators and Operators[-1] != '(' and
Precedence.get(Operators[-1], 0) >= Precedence[token]):
RPNQueue.append(Operators.pop())
Operators.append(token)
while Operators:
RPNQueue.append(Operators.pop())
return RPNQueuebrackets 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