Composition & Closures — Series 3

Preview — 3 of 10 questions

What is the output of the following code?

javascript
from functools import reduce

def safe_divide(acc, x):
    return acc / x

nums = [100, 5, 2, 0, 4]
try:
    result = reduce(safe_divide, nums)
except ZeroDivisionError:
    print("ZeroDivisionError")
print("done")
AZeroDivisionError, done
B0.0, done
CZeroDivisionError
D10.0, done

What is the output of the following code?

javascript
def accumulator():
    total = 0
    while True:
        value = yield total
        total += value

acc = accumulator()
print(next(acc))
print(acc.send(10))
print(acc.send(5))
print(acc.send(-3))
A10, 15, 12, 9
B0, 10, 15, 12
CNone, 10, 15, 12
D0, 10, 15, -3

What is the output of the following code?

javascript
def make_toggle():
    state = False
    def toggle():
        nonlocal state
        state = not state
        return state
    return toggle

t = make_toggle()
print(t())
print(t())
print(t())

t2 = make_toggle()
print(t2())
ATrue, False, True, False
BFalse, True, False, False
CTrue, False, True, True
DTrue, True, True, True

Sign up free to play

Answer all 10 questions (7 more), see explanations for every answer, and track your score.