Lab 5: Sequences and Generators
Due at 11:59pm on 10/30/2016.
Starter Files
Download lab05.zip. Inside the archive, you will find starter files for the questions in this lab, along with a copy of the OK autograder.
Submission
By the end of this lab, you should have submitted the lab using ok
. You may submit more than once before the
deadline; only the final submission will be graded.
Generators
Question 1: Character generator
Write a generator that outputs each character of a string.
def char_gen(s):
"""
>>> for char in char_gen("hello"):
... print(char)
...
h
e
l
l
o
"""
"*** YOUR CODE HERE ***"
for char in s:
yield char
Use OK to test your code:
python ok -q char_gen --local
Question 2: Countdown
Write a generator that counts down to 0.
def countdown(n):
"""
>>> from types import GeneratorType
>>> type(countdown(0)) is GeneratorType # countdown is a generator
True
>>> for number in countdown(5):
... print(number)
...
5
4
3
2
1
0
"""
"*** YOUR CODE HERE ***"
while n >= 0:
yield n
n = n - 1
Use OK to test your code:
python ok -q countdown --local
Question 3: Primes
Write a generator that generates prime numbers.
Fill out the is_prime
helper function and use that
to create your generator.
def is_prime(n):
"""
Return True if n is prime, false otherwise.
>>> is_prime(1)
False
>>> is_prime(2)
True
>>> is_prime(19)
True
"""
"*** YOUR CODE HERE ***"
if n < 2:
return False
counter = 2
while counter <= sqrt(n):
if n % counter == 0:
return False
counter += 1
return True
def primes():
"""
An infinite generator that outputs primes.
>>> p = primes()
>>> for i in range(3):
... print(next(p))
...
2
3
5
"""
"*** YOUR CODE HERE ***"
num = 0
while True:
if is_prime(num):
yield num
num += 1
Use OK to test your code:
python ok -q is_prime --local
Use OK to test your code:
python ok -q primes --local
Question 4: Scale
Implement the generator function scale(s, k)
, which yields elements of the
given iterable s
, scaled by k
.
def scale(s, k):
"""Yield elements of the iterable s scaled by a number k.
>>> s = scale([1, 5, 2], 5)
>>> type(s)
<class 'generator'>
>>> list(s)
[5, 25, 10]
>>> m = scale(naturals(), 2)
>>> [next(m) for _ in range(5)]
[2, 4, 6, 8, 10]
"""
"*** YOUR CODE HERE ***"
for elem in s:
yield elem * k
Use OK to test your code:
python ok -q scale --local
Sequences
Question 5: Count palindromes
def count_palindromes(L):
"""The number of palindromic words in the sequence of strings
L (ignoring case).
>>> count_palindromes(("Acme", "Madam", "Pivot", "Pip"))
2
"""
"*** YOUR CODE HERE ***"
Hint: The easiest way to get the reversed version of a string s
is
to use the Python slicing notation trick s[::-1]
. Also, the function
lower
, when called on strings, converts all of the characters in the
string to lowercase. For instance, if the variable s
contains the
string "PyThoN", the expression s.lower()
evaluates to "python".
Use OK to test your code:
python ok -q count_palindromes --local