#
Homework 11

*Due at 11:59:59 pm on Friday, 4/30/2021.*

## Instructions

Download hw11.zip. Inside the archive, you will find starter files for the questions in this homework, along with a copy of the OK autograder.

**Submission:** When you are done, submit with `python3 ok --submit`

. You may submit more than once before the deadline; only the final submission will be scored. Check that you have successfully submitted your code on okpy.org. See this article for more instructions on okpy and submitting assignments.

**Readings:** This homework relies on following references:

## Iterator/Generator Questions

### Question 1: Restart

Implement an iterator class called `IteratorRestart`

that will reset to the beginning when `__iter__`

is called again.

```
class IteratorRestart:
"""
>>> iterator = IteratorRestart(2, 7)
>>> for num in iterator:
... print(num)
2
3
4
5
6
7
>>> for num in iterator:
... print(num)
2
3
4
5
6
7
"""
def __init__(self, start, end):
"*** YOUR CODE HERE ***"
def __next__(self):
"*** YOUR CODE HERE ***"
def __iter__(self):
"*** YOUR CODE HERE ***"
```

Use OK to test your code:

`python3 ok -q IteratorRestart`

### Question 2: Hailstone

Write a generator that outputs the hailstone sequence from Lab 01.

Here's a quick remainder of how the hailstone sequence is defined:

- Pick a positive integer
`n`

as the start. - If
`n`

is even, divide it by 2. - If
`n`

is odd, multiply it by 3 and add 1. - Continue this process until
`n`

is 1.

```
def hailstone(n):
"""
>>> for num in hailstone(10):
... print(num)
...
10
5
16
8
4
2
1
"""
"*** YOUR CODE HERE ***"
```

Use OK to test your code:

`python3 ok -q hailstone`

### Question 3: Generate permutations

Given a list of unique elements, a *permutation* of the list is a
reordering of the elements. For example, `[2, 1, 3]`

, `[1, 3, 2]`

, and
`[3, 2, 1]`

are all permutations of the list `[1, 2, 3]`

.

Implement `generate_perms`

, a generator function which takes in a `lst`

and yields all the unique permutations of `lst`

one at a time (see doctest for examples).

```
def generate_perms(lst):
"""
Generates the permutations of lst one by one.
>>> perms = generate_perms([1, 2, 3])
>>> hasattr(perms, '__next__')
True
>>> p = list(perms)
>>> p.sort()
>>> p
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
"""
"*** YOUR CODE HERE ***"
```

Use OK to test your code:

`python3 ok -q generate_perms`

## Submit

Make sure to submit this assignment by running:

`python3 ok --submit`