{ "@context": "https://schema.org", "@type": "Organization", "name": "Brainscape", "url": "https://www.brainscape.com/", "logo": "https://www.brainscape.com/pks/images/cms/public-views/shared/Brainscape-logo-c4e172b280b4616f7fda.svg", "sameAs": [ "https://www.facebook.com/Brainscape", "https://x.com/brainscape", "https://www.linkedin.com/company/brainscape", "https://www.instagram.com/brainscape/", "https://www.tiktok.com/@brainscapeu", "https://www.pinterest.com/brainscape/", "https://www.youtube.com/@BrainscapeNY" ], "contactPoint": { "@type": "ContactPoint", "telephone": "(929) 334-4005", "contactType": "customer service", "availableLanguage": ["English"] }, "founder": { "@type": "Person", "name": "Andrew Cohen" }, "description": "Brainscape’s spaced repetition system is proven to DOUBLE learning results! Find, make, and study flashcards online or in our mobile app. Serious learners only.", "address": { "@type": "PostalAddress", "streetAddress": "159 W 25th St, Ste 517", "addressLocality": "New York", "addressRegion": "NY", "postalCode": "10001", "addressCountry": "USA" } }

more skeleton program Flashcards

(14 cards)

1
Q

How does the program handle invalid user input, and what happens to the game state when the user enters an invalid expression?

A

If the input is invalid, CheckIfUserInputValid() returns False, and the program deducts a point from the score.
- targetlist and numbers allowed remain unchanged

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

How does the program manage the Targets list throughout the game, and what is the significance of updating and removing targets from the list?

A
  • 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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

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?

A
  • 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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Explain the process that occurs when the game is over. How is the final score displayed, and what condition causes the game to end?

A
  • 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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

\d+
\s*
what do these do

A

/d+ - Matches one or more digits (numbers).

  • \s* → Matches zero or more spaces (this allows spaces but doesn’t require them).
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

what does “r” before a string do eg:|re.search(r”^(\d+\s[+-*/]\s)+\d+$”, UserInput)

A

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)

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

Brackets question flow

A

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.

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

What regex pattern is used to validate the user input allowing brackets?

A

r”[0-9+-*/()]+”

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

brackets question: how to grab multi-digit numbers (\d+) or any single operator/bracket

A

tokens = re.findall(r’\d+|[()+-*/]’, UserInput)

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

ConvertToRPNWithBrackets ccode modification

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

brackets question : checkvalidoperator function

A

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

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

brackets question: updated checkifuserinputvalid function

A

change
def CheckIfUserInputValid(UserInput):
return re.fullmatch(r”[0-9+-*/()]+”, UserInput) is not None
## end change

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

hint q using brute force (and using more than 2 numbers)

A

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

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

allow user to save

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly