Advertisements
Advertisements
Question
What will happen when following functions are executed?
def fib():
x,y = 1,1
while True:
yield x
x,y = y, x+y
def odd(seq):
for number in seq:
if number % 2:
yield number
def under Four Million(seq):
for number in seq:
if number > 4000000:
break
yield number
print sum(odd(underFourMillion(fib())))Code Writing
Advertisements
Solution
The code as printed will not execute because it has syntax and indentation errors: under Four Million contains spaces, the function should be named underFourMillion, and the if, yield, and print statements need proper indentation.
The corrected Python 3 version is:
def fib():
x, y = 1, 1
while True:
yield x
x, y = y, x + y
def odd(seq):
for number in seq:
if number % 2:
yield number
def underFourMillion(seq):
for number in seq:
if number > 4_000_000:
break
yield number
print(sum(odd(underFourMillion(fib()))))
fib() generates Fibonacci numbers indefinitely. underFourMillion() stops when a number exceeds four million, and odd() keeps only odd numbers. The output is:
4613732
The generator is finite in practice because underFourMillion() stops the iteration.
shaalaa.com
Is there an error in this question or solution?
