Path: blob/master/11-Python Generators/03-Iterators and Generators Homework - Solution.ipynb
666 views
Kernel: Python 3
Iterators and Generators Homework - Solution
Problem 1
Create a generator that generates the squares of numbers up to some number N.
In [1]:
In [2]:
Out[2]:
0
1
4
9
16
25
36
49
64
81
Problem 2
Create a generator that yields "n" random numbers between a low and high number (that are inputs).
Note: Use the random library. For example:
In [3]:
Out[3]:
3
In [4]:
In [5]:
Out[5]:
3
9
6
10
8
4
5
5
5
3
5
8
Problem 3
Use the iter() function to convert the string below into an iterator:
In [6]:
Out[6]:
h
Problem 4
Explain a use case for a generator using a yield statement where you would not want to use a normal function with a return statement.
If the output has the potential of taking up a large amount of memory and you only intend to iterate through it, you would want to use a generator. (Multiple answers are acceptable here!)
Extra Credit!
Can you explain what gencomp is in the code below? (Note: We never covered this in lecture!)
In [7]:
Out[7]:
4
5
Hint: Google generator comprehension!