Advertisement
Diapolo10

Generators

Oct 20th, 2018
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.72 KB | None | 0 0
  1. # Generators and functions have a lot in common; both are defined
  2. # using the def-keyword, and both return values. The main differences
  3. # are that functions return all values at once, whereas generators
  4. # can return values whenever they're needed, saving memory.
  5.  
  6. # Let's say that we wanted to get the fibonacci sequence up to a certain number.
  7.  
  8. # Example function solution
  9. def fibonacci(n):
  10.     nums = []
  11.     a, b = 0, 1
  12.     while a <= n:
  13.         nums.append(a)
  14.         a, b = b, a+b
  15.     return nums
  16.  
  17. # Example generator solution
  18. def fibonacci_gen(n):
  19.     a, b = 0, 1
  20.     while a <= n:
  21.         yield a
  22.         a, b = b, a+b
  23.  
  24. # The yield-keyword is the key to understanding generators.
  25. # It functions almost exactly like return, but doesn't halt the execution.
  26. # In this example, the loop keeps going even after the generator
  27. # returns a value.
  28.  
  29. # Let's count the sum up to 100:
  30. print(sum(fibonacci(100)))
  31. print(sum(fibonacci_gen(100)))
  32.  
  33. # Using small values, the difference in execution speed and
  34. # memory usage aren't very noticeable. But if we were to sum them up
  35. # to 100000, it would be clear that the function would use far
  36. # more memory than the generator. This is simply because generators
  37. # don't have to keep all values in memory at the same time.
  38.  
  39. # Another difference between functions and generators is that you can
  40. # give a value to a generator while it's being used. It's not very common, but
  41. # sometimes it's a very useful tool.
  42.  
  43. def fibonacci_multiply(n):
  44.     a, b = 0, 1
  45.     while a <= n:
  46.         multiplier = yield
  47.         yield a * multiplier
  48.         a, b = b, a+b
  49.  
  50. fib = fibonacci_multiply(100)
  51. n = 0
  52.  
  53. while n <= 100:
  54.     next(fib)
  55.     n = fib.send(42)
  56.     print(n)
  57.  
  58. # It's definitely an advanced concept, but it's useful with multithreading.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement