You may not run any code in Part 1. Once you move to Part 2, you may not return to Part 1.
Note: The Free Response Previews are previews of the question you must solve in Part 2, so that you can choose when to move on from Part 1. You will be able to run code in the testing environment in Part 2. Remember, you will not be able to return to Part 1 once you have moved to Part 2.
Indicate what the following code prints. Place your answers (and nothing else) in the box below. Note that you may not run this code.
def f(s, n, d):
return f'{s}{10*n+d}'
def ct1(n, d=0):
if (n <= 1):
return [f('A', n, d)]
else:
return ct1(n-1, d+1) + [f('B', n, d)] + ct1(n-2, d+1)
print(ct1(3)) # prints a list of 5 strings
Write the recursive function sumSquareEvenDigits(n)
that
returns the sum of the square of the even digits of n. You may assume that n
is a positive integer. For example sumSquareEvenDigits(58474)
returns
96 (8**2+4**2+4**2). If a number has no even digits, return 0.
You may not use strings or loops for this problem.
def sumSquareEvenDigits(n):
return 42
def testSumSquareEvenDigits():
print('Testing sumSquareEvenDigits...', end='')
assert(sumSquareEvenDigits(2) == 4)
assert(sumSquareEvenDigits(1) == 0)
assert(sumSquareEvenDigits(24) == 20)
assert(sumSquareEvenDigits(21) == 4)
assert(sumSquareEvenDigits(212) == 8)
assert(sumSquareEvenDigits(54) == 16)
assert(sumSquareEvenDigits(58474) == 96)
print('Passed!')
testSumSquareEvenDigits()
Background: A "logic gate" is a piece of hardware which implements a boolean operator (like and
or or
).
Write the class Gate (implementing the logic gates AND, OR) and the child class NegatedGate (implementing the logic gates NAND, NOR, which have the opposite return values of AND, OR) that pass the following test cases. You may not hardcode any test cases.
Important: The method eval
of the class
NegatedGate must call the method in its parent class.
def testGateAndNegatedGate():
print('Testing Gate and NegatedGate...', end='')
gate1 = Gate('and') # (type of gate)
assert((gate1.eval(True, True) == True) and (gate1.eval(True, False) == False))
gate2 = Gate('or')
assert((gate2.eval(True, False) == True) and (gate2.eval(False, True) == True))
assert(str(gate1) == 'and gate')
assert(str(NegatedGate('and')) == 'Nand gate')
gate3 = NegatedGate('or') # Nor gate
assert(isinstance(gate3, Gate))
assert((gate3.eval(False, True) == False) and (gate3.eval(False, False) == True))
assert(str(gate3) == 'Nor gate')
assert(gate1 == Gate('and'))
assert(gate1 != NegatedGate('and'))
assert(gate1 != 'and gate') # don't crash!
assert(gate3 == gate3)
s = set()
s.add(NegatedGate('or'))
assert(gate3 in s)
s.add(Gate('and'))
print('Passed!')
testGateAndNegatedGate()