more on for loops (slides)

CSc 110 - more on for loops lists

lists within lists

We’ve worked with lists of integers, list of strings, and lists of floats – but we can also have lists of lists:

lists = [[9,  8,  7,  8],
         [10, 20, 30, 4],
         [5,  50, 55, 4]]
lists[0]
[9, 8, 7, 8]
lists[0][0]
9

2D lists

  • The “first dimension”: index of the outer list
  • The “second dimension”: index of the inner list
lists = [[9,  8,  7,  8], # index 0 of outer list
         [10, 20, 30, 4], # index 1 of outer list
         [5,  50, 55, 4]] # index 2 of outer list

2D lists

  • When we draw pictures of 2D lists, the first dimension is the vertical axis, the second is the horizontal
lists = [[9,  8,  7,  8],
         [10, 20, 30, 4],
         [5,  50, 55, 4]]

Evaluate the Expressions

numbers = [[4, 2, 3],
           [0, 2, 5]]
numbers[1][2]   

items = [[9, 7, 8],
         [1, 2, 3, 4, 5, 6],
         [5],
         [10, 20, 30]]
items[1][5]
items[2][5]
items[3][2]

Evaluate the Expressions

numbers = [[4, 2, 3],
           [0, 2, 5]]
numbers[1][2]
5
items = [[9, 7, 8],
         [1, 2, 3, 4, 5, 6],
         [5],
         [10, 20, 30]]
items[1][5]
6
items[2][5] # will throw error
items[3][2]
30

for loops with lists of lists

items = [[9, 7, 8],
         [5],
         [10, 20, 30]]
         
for i in range(len(items)):
  print(items[i])
  for j in range(len(items[i])):
    print( items[i][j] )
[9, 7, 8]
9
7
8
[5]
5
[10, 20, 30]
10
20
30

Write a function

It returns a single list that flattens that list of lists into a single list that contains exactly the same values. Do not use any list methods besides .append().

assert flatten([]) == []
assert flatten([[1, 2, 3], [4, 5, 6]]) == [1, 2, 3, 4, 5, 6]
assert flatten([[1, 2, 3], [4]]) == [1, 2, 3, 4]

Write a function – solution

def flatten(numbers):
  new_list = []
  for i in range(len(numbers)):
    for j in range(len(numbers[i])):
      new_list.append(numbers[i][j])
  return new_list

def main():
  assert flatten([]) == []
  assert flatten([[1, 2, 3], [4, 5, 6]]) == [1, 2, 3, 4, 5, 6]
  assert flatten([[1, 2, 3], [4]]) == [1, 2, 3, 4]

main()

Write a function

It takes an argument, lists, which is a 2D list of numbers (floats or integers) and calculates the average of each sublist, and returns the highest average.

Name file two_d_highest_average.py and submit to gradescope.

assert get_highest_average([[1, 1, 1], [2, 2]]) == 2
assert get_highest_average([[], []]) == None
assert get_highest_average([]) == None

Write a function – solution 1

An illustration:

%%{init: {'theme': 'base', 'themeVariables': { 'fontSize': '24px', 'fontFamily': 'Inter'}}}%%

flowchart LR
  A["[[ ],  <br>  [2, 3, 7], <br> [15, 21, 3, 24], <br> [6, 4] ]"] --> B("len([]) > 0 ?") 
  A --> SS("len([2, 3, 7]) > 0 ?") --> id1[calculate mean: 4] --> E1[highest mean: 4]
  A --> SSS("len([15, 2, 3, 8]) > 0 ?") --> id2[calculate mean: 7] --> E2[highest mean: 7]
  A --> SSSS("len([6, 4]) > 0 ?") --> id3[calculate mean: 5]--> E3[highest mean: 7]
  

  style id1 fill:#ffd5f1,stroke:#333,stroke-width:2px
  style id2 fill:#ffd5f1,stroke:#333,stroke-width:2px
  style id3 fill:#ffd5f1,stroke:#333,stroke-width:2px
  style E1 fill:#feffad,stroke:#333,stroke-width:2px
  style E2 fill:#feffad,stroke:#333,stroke-width:2px
  style E3 fill:#feffad,stroke:#333,stroke-width:2px

Write a function – solution 1

def get_highest_average(numbers):
    highest_mean = None
    for i in range(len(numbers)):
        if len(numbers[i]) > 0:
            total = 0
            for j in range(len(numbers[i])):
                total += numbers[i][j]
            mean = total/len(numbers[i])
            if highest_mean == None or mean > highest_mean:
                highest_mean = mean
    return highest_mean

def main():
  assert get_highest_average([[1, 1, 1], [2, 2]]) == 2
  assert get_highest_average([[1, 1, 1], []]) == 1
  assert get_highest_average([[], []]) == None
  assert get_highest_average([]) == None
  
  weeks = [ [100, 100, 105, 105, 102, 102, 100],
            [70, 71, 75, 72, 81, 80, 74],
            [78, 72, 74, 71, 70, 70, 70],
            [30, 32, 40, 38, 31, 32, 30] ]
  average = get_highest_average(weeks)
  assert average == 102
  
main()

Write a function – solution 2

An illustration:

%%{init: {'theme': 'base', 'themeVariables': { 'fontSize': '24px', 'fontFamily': 'Inter'}}}%%

flowchart LR
  A["[[ ],  <br>  [2, 3, 7], <br> [15, 21, 3, 24], <br> [6, 4] ]"] --> B("len([]) > 0 ?") 
  A --> SS("len([2, 3, 7]) > 0 ?") --> id1[calculate mean: 4]
  A --> SSS("len([15, 2, 3, 8]) > 0 ?") --> id2[calculate mean: 7]
  A --> SSSS("len([6, 4]) > 0 ?") --> id3[calculate mean: 5]
  id1 --> E["[4, 7, 5]"]
  id2 --> E
  id3 --> E
  
  E --> id4[highest mean: 7]
  

  style id1 fill:#ffd5f1,stroke:#333,stroke-width:2px
  style id2 fill:#ffd5f1,stroke:#333,stroke-width:2px
  style id3 fill:#ffd5f1,stroke:#333,stroke-width:2px
  style id4 fill:#feffad,stroke:#333,stroke-width:2px

Write a function – solution 2

def max_list(numbers):
  max = None
  for n in numbers:
    if max == None or n > max:
      max = n
  return max

def get_highest_average(lists):
    means = []
    highest_mean = None
    for i in range(len(lists)):
        if len(lists[i]) > 0:
            total = 0
            for j in range(len(lists[i])):
                total += lists[i][j]
            mean = total/len(lists[i])
            means.append(mean)
    highest_mean = max_list(means)
    return highest_mean

def main():
    assert get_highest_average([[1, 1, 1], [2, 2]]) == 2
    assert get_highest_average([[1, 1, 1], []]) == 1
    assert get_highest_average([[], []]) == None
    assert get_highest_average([]) == None
    
    weeks = [ [100, 100, 105, 105, 102, 102, 100],
              [70, 71, 75, 72, 81, 80, 74],
              [78, 72, 74, 71, 70, 70, 70],
              [30, 32, 40, 38, 31, 32, 30] ]
    average = get_highest_average(weeks)
    assert average == 102
  
main()