proffreda

lab10.py

Apr 13th, 2017
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.11 KB | None | 0 0
  1. #############
  2. # Iterators #
  3. #############
  4.  
  5. # Q3
  6. class Str:
  7. """
  8. >>> s = Str("hello")
  9. >>> for char in s:
  10. ... print(char)
  11. ...
  12. h
  13. e
  14. l
  15. l
  16. o
  17. >>> for char in s: # a standard iterator does not restart
  18. ... print(char)
  19. """
  20. "*** YOUR CODE HERE ***"
  21.  
  22. ##############
  23. # Generators #
  24. ##############
  25.  
  26. # Q5
  27. def scale(s, k):
  28. """Yield elements of the iterable s scaled by a number k.
  29.  
  30. >>> s = scale([1, 5, 2], 5)
  31. >>> type(s)
  32. <class 'generator'>
  33. >>> list(s)
  34. [5, 25, 10]
  35.  
  36. >>> m = scale(naturals(), 2)
  37. >>> [next(m) for _ in range(5)]
  38. [2, 4, 6, 8, 10]
  39. """
  40. "*** YOUR CODE HERE ***"
  41.  
  42. # Q6
  43. def countdown(n):
  44. """
  45. A generator that counts down from N to 0.
  46. >>> for number in countdown(5):
  47. ... print(number)
  48. ...
  49. 5
  50. 4
  51. 3
  52. 2
  53. 1
  54. 0
  55. >>> for number in countdown(2):
  56. ... print(number)
  57. ...
  58. 2
  59. 1
  60. 0
  61. """
  62. "*** YOUR CODE HERE ***"
  63.  
  64. class Countdown:
  65. """
  66. An iterator that counts down from N to 0.
  67. >>> for number in Countdown(5):
  68. ... print(number)
  69. ...
  70. 5
  71. 4
  72. 3
  73. 2
  74. 1
  75. 0
  76. >>> for number in Countdown(2):
  77. ... print(number)
  78. ...
  79. 2
  80. 1
  81. 0
  82. """
  83. def __init__(self, cur):
  84. self.cur = cur
  85.  
  86. def __next__(self):
  87. "*** YOUR CODE HERE ***"
  88.  
  89. def __iter__(self):
  90. """So that we can use this iterator as an iterable."""
  91. return self
  92.  
  93. # Q7
  94. def hailstone(n):
  95. """
  96. >>> for num in hailstone(10):
  97. ... print(num)
  98. ...
  99. 10
  100. 5
  101. 16
  102. 8
  103. 4
  104. 2
  105. 1
  106. """
  107. "*** YOUR CODE HERE ***"
  108.  
  109. # the naturals generator is used for testing scale and merge functions
  110. def naturals():
  111. """A generator function that yields the infinite sequence of natural
  112. numbers, starting at 1.
  113.  
  114. >>> m = naturals()
  115. >>> type(m)
  116. <class 'generator'>
  117. >>> [next(m) for _ in range(10)]
  118. [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  119. """
  120. i = 1
  121. while True:
  122. yield i
  123. i += 1
Advertisement
Add Comment
Please, Sign In to add comment