Jun-10-2020, 02:58 PM
Misunderstanding. You meant to have values in the list which are lower than 100.
My example creates a list with exactly 100 elements.
You compared
You've to compare
Not bigger than 50 and maximum 10 elements:
There is no stop condition. Only the decision is made to take x or not.
My example creates a list with exactly 100 elements.
You compared
j > 100
, which is not the final value.You've to compare
(x[-1] + x[-2]) >= 100
.x = [0, 1] for j in x: result = x[-1] + x[-2] if result >= 100: # stop is result is bigger or equal to 100 break x.append(result) print(x)With my provided example:
from itertools import takewhile, islice def fib(): a, b = 0, 1 while True: yield a a, b = a + b, a def condition(value): return value < 100 generator = fib() fibs_below_100 = list(takewhile(condition, generator))And you can combine different functions from itertools.
Not bigger than 50 and maximum 10 elements:
fib_gen = fib() fibs_below_50 = takewhile(lambda x: x < 100, fib_gen) fibs_max_10_elements = islice(fibs_below_50 , 0, 10) final_result = list(fibs_max_10_elements)There is one big pitfall, if you use infinite generators:
[x for x in fib if x < 100]This code will run until you get a MemoryError or hit CTRL+C.
There is no stop condition. Only the decision is made to take x or not.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
All humans together. We don't need politicians!