Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Generators and functions have a lot in common; both are defined
- # using the def-keyword, and both return values. The main differences
- # are that functions return all values at once, whereas generators
- # can return values whenever they're needed, saving memory.
- # Let's say that we wanted to get the fibonacci sequence up to a certain number.
- # Example function solution
- def fibonacci(n):
- nums = []
- a, b = 0, 1
- while a <= n:
- nums.append(a)
- a, b = b, a+b
- return nums
- # Example generator solution
- def fibonacci_gen(n):
- a, b = 0, 1
- while a <= n:
- yield a
- a, b = b, a+b
- # The yield-keyword is the key to understanding generators.
- # It functions almost exactly like return, but doesn't halt the execution.
- # In this example, the loop keeps going even after the generator
- # returns a value.
- # Let's count the sum up to 100:
- print(sum(fibonacci(100)))
- print(sum(fibonacci_gen(100)))
- # Using small values, the difference in execution speed and
- # memory usage aren't very noticeable. But if we were to sum them up
- # to 100000, it would be clear that the function would use far
- # more memory than the generator. This is simply because generators
- # don't have to keep all values in memory at the same time.
- # Another difference between functions and generators is that you can
- # give a value to a generator while it's being used. It's not very common, but
- # sometimes it's a very useful tool.
- def fibonacci_multiply(n):
- a, b = 0, 1
- while a <= n:
- multiplier = yield
- yield a * multiplier
- a, b = b, a+b
- fib = fibonacci_multiply(100)
- n = 0
- while n <= 100:
- next(fib)
- n = fib.send(42)
- print(n)
- # It's definitely an advanced concept, but it's useful with multithreading.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement