Lecture 7 – Iteration, Part 1

Data 94, Spring 2021

Motivating demos

In [1]:
name = 'billy'
In [2]:
name = name + name
name
Out[2]:
'billybilly'

Let's try something cool!

In [3]:
f = open('data/words.txt', 'r')
dictionary = f.read().split('\n')
In [4]:
user_word = input('Enter a word (or hit enter to stop): ')
in_count = 0
out_count = 0
while user_word:
    if user_word in dictionary:
        print(user_word + ' is in the dictionary!\n')
        in_count += 1
    else:
        print(user_word + ' is not in the dictionary.\n')
        out_count += 1

    user_word = input('Enter a word (or hit enter to stop): ')
    
print(f'\nWord(s) in dictionary:     {in_count}\nWord(s) not in dictionary: {out_count}')
Enter a word (or hit enter to stop): 

Word(s) in dictionary:     0
Word(s) not in dictionary: 0

While loop fundamentals

In [5]:
i = 0
while i < 10:
    print(i)
    i = i + 1
print('blastoff!')
0
1
2
3
4
5
6
7
8
9
blastoff!

Example: sum_first_n

In [6]:
def sum_first_n(n):
    j = 1
    total = 0
    while j <= n:
        total += j
        j += 1
    return total
In [7]:
# 1 + 2 + 3 + 4
sum_first_n(4)
Out[7]:
10

Example: sum_first_n_no_threes

In [8]:
def sum_first_n_no_threes(n):
    j = 1
    total = 0
    while j <= n:
        # If j is not a multiple of 3
        if j % 3 != 0:
            total += j
        j += 1
    return total
In [9]:
# 1 + 2 + 4 + 5
sum_first_n_no_threes(6)
Out[9]:
12

Quick Check 1

In [10]:
def doubling_time(pop, r):
    start = ...
    t = 0
    while start < 2 * pop:
        start = ...
        t += 1
    return t
In [ ]:
 

More Examples

Fibonacci sequence

$$0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ...$$
In [11]:
def fib(n):
    prev, curr = 0, 1
    i = 1
    while i < n:
        prev, curr = curr, prev + curr
        i += 1
    return curr
In [12]:
fib(7)
Out[12]:
13
In [13]:
fib(243)
Out[13]:
271964099255182923543922814194423915162591622175362

It turns out there's a formula that we can use to compute the $n$-th Fibonacci number, without iteration:

$$F_n = \frac{\phi^{n} - (1 - \phi)^{n}}{\sqrt{5}}$$

where $\phi = \frac{1 + \sqrt{5}}{2}$ is the "Golden Ratio".

In [14]:
golden = (1 + 5**0.5) / 2
golden
Out[14]:
1.618033988749895
In [15]:
def fib_no_iteration(n):
    return int((golden**n - (1 - golden)**n) / (5**0.5))
In [16]:
fib_no_iteration(7)
Out[16]:
13

Prime factorization

Let's first define smallest_factor, a function that takes in a positive integer n and returns the smallest factor of n. (This number is prime!)

In [17]:
# One implementation
def smallest_factor(n):
    k = 2
    while k <= n:
        if n % k == 0:
            return k
        k += 1
        
# An equivalent implementation
def smallest_factor(n):
    k = 2
    while n % k != 0:
        k += 1
    return k
In [18]:
smallest_factor(5)
Out[18]:
5
In [19]:
smallest_factor(24)
Out[19]:
2

Now, let's define prime_factors, a function that takes in a positive integer n and prints all of the prime factors of n.

In [20]:
def prime_factors(n):
    while n > 1:
        k = smallest_factor(n)
        print(k)
        n = n // k
In [21]:
prime_factors(22)
2
11
In [22]:
prime_factors(144)
2
2
2
2
3
3

Dictionary Demo

User Input

In [23]:
name = input('Enter your name: ')
print('Hi, ' + name + '!')
Enter your name: 
Hi, !
In [24]:
user_word = input('Enter a word (or hit enter to stop): ')
in_count = 0
out_count = 0
while user_word:
    if user_word in dictionary:
        print(user_word + ' is in the dictionary!\n')
        in_count += 1
    else:
        print(user_word + ' is not in the dictionary.\n')
        out_count += 1

    user_word = input('Enter a word (or hit enter to stop): ')
    
print(f'\nWord(s) in dictionary:     {in_count}\nWord(s) not in dictionary: {out_count}')
Enter a word (or hit enter to stop): 

Word(s) in dictionary:     0
Word(s) not in dictionary: 0