Lecture 12 – More Iteration

Data 94, Spring 2021

Review

In [1]:
for n in [2, 4, 6, 8]:
    print(n * 5)
10
20
30
40

Quick Check 1

In [ ]:
 

While vs. for

In [2]:
def sum_squares_for(values):
    total = 0
    for v in values:
        total += v**2
    return total

# 3^2 + 4^2 + 5^2
sum_squares_for([3, 4, 5])
Out[2]:
50
In [3]:
def sum_squares_while(values):
    total = 0
    j = 0
    while j < len(values):
        total += values[j]**2
        j += 1
    return total

# 3^2 + 4^2 + 5^2
sum_squares_while([3, 4, 5])
Out[3]:
50
In [ ]:
 
In [ ]:
 

Example: missing number

Quick Check 2

In [ ]:
def missing_number(nums):
    for ...:
        if n not in nums:
            return n
In [ ]:
# Should be 3
missing_number([1, 2, 6, 4, 5])
In [ ]:
# Should be 6
missing_number([7, 2, 3, 5, 9, 8, 4, 1])

Example: Luhn's algorithm

In [4]:
# Ignore this code
def int_to_list(n):
    return [int(i) for i in str(n)]
In [5]:
int_to_list(5457623898234113)
Out[5]:
[5, 4, 5, 7, 6, 2, 3, 8, 9, 8, 2, 3, 4, 1, 1, 3]
In [6]:
def luhns_algorithm(cc):
    # Step 1
    check_digit = cc[-1]
    
    even_sum = 0
    for i in range(0, len(cc), 2):
        # Step 2
        even_element = cc[i] * 2
        if even_element > 9:
            even_element = even_element - 9
            
        # Step 3
        even_sum += even_element
    
    # Step 4
    odd_sum = 0
    for i in range(1, len(cc) - 2, 2):
        odd_sum += cc[i]
        
    # Step 5
    total_sum = even_sum + odd_sum
    
    # Step 6
    return (total_sum + check_digit) % 10 == 0
In [7]:
luhns_algorithm(int_to_list(5457623898234113))
Out[7]:
True

What if I accidentally swap two digits?

In [8]:
luhns_algorithm(int_to_list(5475623898234113))
Out[8]:
False

Now Luhn's algorithm can tell me the credit card number is invalid, which likely means I made a typo.

Nested loops and lists

Example: times tables

In [9]:
for x in range(1, 5):
    for y in range(1, 5):
        print(str(x) + ' x ' + str(y) 
              + ' = ' + str(x * y))
1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
1 x 4 = 4
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
3 x 4 = 12
4 x 1 = 4
4 x 2 = 8
4 x 3 = 12
4 x 4 = 16

Example: movies

In [10]:
movies = [['21 Jump Street', 'Grown Ups', 'Mall Cop'],
          ['Paranormal Activity', 'Nightmare on Elm Street'],
          ['Crazy Rich Asians', 'Trainwreck', 'Crazy, Stupid, Love']]
In [11]:
for genre in movies:
    for movie in genre:
        print(movie)
    print('---')
21 Jump Street
Grown Ups
Mall Cop
---
Paranormal Activity
Nightmare on Elm Street
---
Crazy Rich Asians
Trainwreck
Crazy, Stupid, Love
---
In [12]:
movies[0][2]
Out[12]:
'Mall Cop'