Question: Pyhton code! Using the Stream class we defined in the lecture, write a function streamRandoms(k,min,max) that creates an infinite stream of positive random integers starting
Pyhton code!
Using the Stream class we defined in the lecture, write a function streamRandoms(k,min,max) that creates an infinite stream of positive random integers starting at k (i.e., make the first element of the stream k). The values in the stream should be randomly generated and each value should be between min and max argument values (inclusive). (You may make use of the random.randint(a,b) method to generate random integers. To get access to the random module, you need to add the line import random in your program.)
For example:
>>> rStream = streamRandoms(1,1,100)
>>> myList = []
>>> for i in range (0,10):
myList.append(rStream.first)
rStream = rStream.rest
After running the above code, myList should include the first 10 values of the rStream. (for example: [1, 28, 2, 33, 72, 96, 1, 85, 56, 31])
You can start with the following code:
def streamRandoms (k,min,max):
#write your code here
Stream class:
class Stream(object):
def __init__(self, first, compute_rest, empty= False):
self.first = first
self._compute_rest = compute_rest
self.empty = empty
self._rest = None
self._computed = False
@property
def rest(self):
assert not self.empty, 'Empty streams have no rest.'
if not self._computed:
self._rest = self._compute_rest()
self._computed = True
return self._rest
empty_stream = Stream(None, None, True)
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
