Docsity

CPSC 121 Fall 2012 Lecture Notes: Random Numbers and Sublist Sum, Study notes of Computer Science

Partial preview of the text

Download CPSC 121 Fall 2012 Lecture Notes: Random Numbers and Sublist Sum and more Study notes Computer Science in PDF only on Docsity!

Today ...

  • Random numbers

Homework

  • HW 7 due
  • HW 8 out

Exercise: More nested loop practice

Write a function called sublist sum(a list) that takes a list whose elements are lists of ints and returns the sum of all the values in each sublist. For example:

sublist_sum([[1,2], [2,3], [3,4]]) 15

sublist_sum([[1,2,3], [4,5,6]]) 21

Hint: Use a nested loop! Use either value loops or range loops

Answer:

def sublist_sum(a_list): total = 0 for sublist in a_list: for elem in sublist: total = total + elem return total