Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!
sum(i for i in range(10))45set(i for i in range(10)){0, 1, 2, 3, 4, 5, 6, 7, 8, 9}[i for i in range(10)][0, 1, 2, 3, 4, 5, 6, 7, 8, 9]list(i for i in range(10))[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]{i for i in range(10)}{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}Must use () to get a generator.
Exception is raised without ().
# this is NOT tuple!!!
(i for i in range(10))<generator object <genexpr> at 0x7f2f84630938>i for i in range(10) File "<ipython-input-1-b07d337502b5>", line 1
i for i in range(10)
^
SyntaxError: invalid syntax
import itertools as it
def fibonacci(x1, x2):
while True:
yield x1
x1, x2 = x2, x1 + x2
fiter = fibonacci(1, 1)
list(it.islice(fiter, 0, 10))[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]fiter = fibonacci(1, 1)
list(it.takewhile(lambda x: x < 100, fiter))[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]Comment¶
yield cannot be used recursively.
Do NOT use iterator to mimic generator as iterator is not lazy evaluation.
def fib2(x1, x2):
yield x1
return fibonacci(x2, x1 + x2)fiter2 = fib2(1, 1)
list(it.islice(fiter2, 0, 10))[1]import itertools as it
def fib3(x1, x2):
it.chain([x1], fib3(x2, x1 + x2))fib3(1, 1)---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
<ipython-input-35-800beaf116b0> in <module>()
----> 1 fib3(1, 1)
<ipython-input-34-91b9f12414a5> in fib3(x1, x2)
2
3 def fib3(x1, x2):
----> 4 it.chain([x1], fib3(x2, x1 + x2))
... last 1 frames repeated, from the frame below ...
<ipython-input-34-91b9f12414a5> in fib3(x1, x2)
2
3 def fib3(x1, x2):
----> 4 it.chain([x1], fib3(x2, x1 + x2))
RuntimeError: maximum recursion depth exceeded