http://www.cs.cornell.edu/courses/cs0/08sp Lecture : Iteration and For-Loops (Sections 4. and 0.3) CS 0 Introduction to Computing Using Python [E. Andersen, A. Bracy, D. Gries, L. Lee, S. Marschner, C. Van Loan, W. White]
Announcements: Prelim Rooms: AA JKZ99999 Baker Laboratory 00 JL SEZ99999 Rockefeller 0 SF ZZ999999 Rockefeller 03 covers material up through today What to study: A, A, Labs -6, old exam questions: Prelim study guide on webpage under Exams If you requested a makeup via CMS you will receive an emailed today about whether the request is granted. Email SDS letters to cs0-prof@cornell.edu, and Cc: Jenna Edwards jls478@cornell.edu
Announcements Don t skip lab! (especially not this lab!) A Due Thursday. Solutions released Friday A must be submitted as a PDF Convert your files to pdf with Genius Scan https://www.thegrizzlylabs.com/genius-scan/ 3
More Announcements Lab 6: due in two weeks Tuesday 3/3 labs: open office hours Wednesday 3/4 labs: cancelled Thursday 3/8: optional in-class review session Tuesday 3/3: no lecture; office hours instead Olin 55 during class times, Olin 8 in between A3: released sometime after Prelim 4
Advice from Consultants about A Tests Cases Test for: all possible input patterns all possible outputs you might expect Remember: Space is not the same thing as the empty string When you are thinking of test cases, write comments next to them explaining why you think they are different from the other cases. This will help you come up with distinct test cases. 5
Problem: Summing the Elements of a List def sum(the_list): """Returns: the sum of all elements in the_list Precondition: the_list is a list of all numbers (either floats or ints)""" 6
Approach: Summing the Elements of a List def sum(the_list): """Returns: the sum of all elements in the_list Precondition: the_list is a list of all numbers (either floats or ints)""" # Create a variable to hold result (start at 0) # Add each list element to variable # Return the variable How will we do this? 7
st Attempt: Summing the Elements of a List def sum(the_list): """Returns: the sum of all elements in the_list Precondition: the_list is a list of all numbers (either floats or ints)""" result = 0 result = result + the_list[0] result = result + the_list[] return result Houston, we have a problem 8
Working with Sequences Sequences are potentially unbounded Number of elements is not fixed Functions must handle sequences of different lengths Example: sum([,,3]) vs. sum([4,5,6,7,8,9,0]) Cannot process with fixed number of lines Each line of code can handle at most one element What if there are millions of elements? We need a new approach 9
For Loops: Processing Sequences for x in grades: print(x) loop sequence: grades loop variable: x body: print(x) To execute the for-loop:. Check if there is a next element of loop sequence grades has more elements True put next element in x. If so: assign next sequence element to loop variable False print(x) Execute all of the body Go back to Line 3. If not, terminate execution 0
Solution: Summing the Elements of a List def sum(the_list): """Returns: the sum of all elements in the_list Precondition: the_list is a list of all numbers (either floats or ints)""" result = 0 Accumulator variable for x in the_list: result = result + x return result loop sequence: the_list loop variable: x body: result=result+x
What gets printed? (Q) a = 0 a = 0 a = 0 a = 0 for b in []: for b in [, ]: for b in [,, 3]: for b in [,, 3]: a = a + a = a + a = a + a = b print(a) print(a) print(a) print(a)
What gets printed? (A) a = 0 a = 0 a = 0 a = 0 for b in []: for b in [, ]: for b in [,, 3]: for b in [,, 3]: a = a + a = a + a = a + a = b print(a) print(a) print(a) print(a) 3 3 3
What gets printed? (Q) a = 0 for b in [,, 3]: a = a + b print(a) a = 0 b = [,, 3] for c in b: a = a + c print(a) a = 0 b = [,, 3] for c in b: a = a + c print(b) 4
What gets printed? (A) a = 0 for b in [,, 3]: a = a + b print(a) a = 0 b = [,, 3] for c in b: a = a + c print(a) a = 0 b = [,, 3] for c in b: a = a + c print(b) 6 6 [,, 3] 5
For Loops and Conditionals def num_ints(the_list): """Returns: the number of ints in the_list Precondition: the_list is a list of any mix of types""" result = 0 for x in the_list: if type(x) == int: result = result+ return result # Create variable to hold result # for each element in the list # check if it is an int # add if it is # Return the variable 6
For Loop with labels def num_ints(the_list): """Returns: the number of ints in the_list Precondition: the_list is a list of any mix of types""" result = 0 for x in the_list: if type(x) == int: result = result+ return result Accumulator variable Loop sequence Loop variable Body 7
What if we aren t dealing with a list? So far we ve been building for-loops around elements of a list. What if we just want to do something some number of times? range to the rescue! 8
range: a handy counting function! range(x) returns 0,,,x- range(a,b) returns a,,b- >>>first_six = list(range(6)) >>> print(first_six) [0,,, 3, 4, 5] >>> second_six = list(range(6,3)) >>> print(second_six) [6, 7, 8, 9, 0,, ] Important: range does not return a list à need to convert ranges return value into a list 9
range in a for-loop, v for num in list(range(0)): line = "The ants go marching "+str(num)+" by "+str(num) for y in list(range()): print(line+" Hurrah! Hurrah!") print(line+", blah blah something that rhymes with "+str(num)) print("and they all go marching down into the ground") print(" to get out of the rain\n") Anything weird here? (Kids don t usually count from 0.) 0
range in a for-loop, v for num in list(range(0)): list(range(,)): line = "The ants go marching "+str(num)+" by "+str(num) for y in list(range()): print(line+" Hurrah! Hurrah!") print(line+", blah blah something that rhymes with "+str(num)) print("and they all go marching down into the ground") print(" to get out of the rain\n") Ahh, much better.
Roses # at our year anniversary my partner gave me a rose # and promised to give me more rose each year thereafter # how many roses will that be?! met_year = 003 n_years = 75 total_roses = 0 for n_years in list(range(, n_years+)): print(str(met_year+n_years)+ : "+str(n_years)+" roses") total_roses = total_roses + n_years print("after "+str(n_years)+" years: "+str(total_roses)+" roses!")
What gets printed? (Q3) a = 0 for b in range(0, ): a = a + a = 0 for b in range(0, 4): a = a + print(a) print(a) 3
What gets printed? (A3) a = 0 for b in range(0, ): a = a + a = 0 for b in range(0, 4): a = a + print(a) print(a) 4 4
Modifying the Contents of a List def add_one(the_list): """Adds to every element in a list of all numbers (either floats or ints)""" size = len(the_list) for k in list(range(size)): the_list[k] = the_list[k]+ grades = [8,9,0,5,9,0] print("initial grades are: "+str(grades)) add_one(grades) print("inflated grades are: "+str(grades)) 5
The Map Function map( function, list ) function takes parameter Otherwise, error map(f, [a,b,c,d]) f(a), f(b), f(c), f(d) Important: map does not return a list à need to convert map s return value into a list >>> len_list = list(map(len, ['a', 'bc', 'defg ])) >>> len_list [,, 4] 6
The Filter Function filter( Boolean_function, list ) function takes parameter function returns a Boolean Collects elements of list for which Boolean_function returns True filter(f, [a,b,c]) a if f(a)==true, b if f(b)==true, c if f(c)==true, Important: filter does not return a list à need to convert map s return value into a list See ints.py to see filter in action 7
Never modify: Common For-Loop Mistakes () the loop sequence (or the list of indices) as you walk through it () the loop variable See examples on following slides. 8
For-Loop Mistake # (Q) Modifying the loop sequence as you walk through it. b = [,, 3] for a in b: b.append(a) A: never prints b B: [,, 3,,, 3] C: [,, 3] D: I do not know print b 9
b = [,, 3] for a in b: b.append(a) For-Loop Mistake # (A) Modifying the loop sequence as you walk through it. INFINITE LOOP! A: never prints b B: [,, 3,,, 3] C: [,, 3] D: I do not know CORRECT* print b * Runs out of memory eventually, then probably throws an error. 30
For-Loop Mistake # (Q) Modifying the loop variable (here: x). def add_one(the_list): """Adds to every element in the list Precondition: the_list is a list of all numbers (either floats or ints)""" for x in the_list: x = x+ a = [5, 4, 7] add_one(a) print(a) What gets printed? A: [5, 4, 7] B: [5, 4, 7, 5, 4, 7] C: [6, 5, 8] D: Error E: I don t know 3
For-Loop Mistake # (A) Modifying the loop variable (here: x). def add_one(the_list): """Adds to every element in the list Precondition: the_list is a list of all numbers (either floats or ints)""" for x in the_list: x = x+ a = [5, 4, 7] add_one(a) print(a) Actually it does not do this! What gets printed? A: [5, 4, 7] B: [5, 4, 7, 5, 4, 7] C: [6, 5, 8] D: Error E: I don t know CORRECT 3
Modifying the Loop Variable () def add_one(the_list): """Adds to every elt Pre: the_list is all numb.""" for x in the_list: x = x+ grades = [5,4,7] add_one(grades) Global Space grades id4 Call Frame add_one the_list id4 0 Heap Space id4 5 4 7 33
Modifying the Loop Variable () def add_one(the_list): """Adds to every elt Pre: the_list is all numb.""" for x in the_list: x = x+ grades = [5,4,7] add_one(grades) Global Space grades id4 Call Frame add_one the_list id4 x 5 0 Heap Space id4 5 4 7 34
Modifying the Loop Variable (3) def add_one(the_list): """Adds to every elt Pre: the_list is all numb.""" for x in the_list: x = x+ Loop back to line Global Space grades id4 0 Heap Space id4 5 4 7 Call Frame grades = [5,4,7] add_one add_one(grades) the_list id4 Increments x in frame Does not affect folder x 6 35
Modifying the Loop Variable (4) def add_one(the_list): """Adds to every elt Pre: the_list is all numb.""" for x in the_list: x = x+ Global Space grades id4 0 Heap Space id4 5 4 7 Call Frame grades = [5,4,7] add_one add_one(grades) the_list id4 Next element stored in x. Previous calculation lost. x 4 36
Modifying the Loop Variable (5) def add_one(the_list): """Adds to every elt Pre: the_list is all numb.""" for x in the_list: x = x+ grades = [5,4,7] add_one(grades) Loop back to line Global Space grades id4 Call Frame add_one the_list id4 x 5 0 Heap Space id4 5 4 7 37
Modifying the Loop Variable (6) def add_one(the_list): """Adds to every elt Pre: the_list is all numb.""" for x in the_list: x = x+ Global Space grades id4 0 Heap Space id4 5 4 7 Call Frame grades = [5,4,7] add_one add_one(grades) the_list id4 Next element stored in x. Previous calculation lost. x 7 38
Modifying the Loop Variable (7) def add_one(the_list): """Adds to every elt Pre: the_list is all numb.""" for x in the_list: x = x+ grades = [5,4,7] add_one(grades) Loop back to line Global Space grades id4 Call Frame add_one the_list id4 x 8 0 Heap Space id4 5 4 7 39
Modifying the Loop Variable (8) def add_one(the_list): """Adds to every elt Pre: the_list is all numb.""" for x in the_list: x = x+ Global Space grades id4 0 Heap Space id4 5 4 7 Call Frame grades = [5,4,7] add_one(grades) add_one the_list id4 Loop is completed. Nothing new put in x. x 8 RETURN NONE 40
Modifying the Loop Variable (9) def add_one(the_list): """Adds to every elt Pre: the_list is all numb.""" for x in the_list: x = x+ grades = [5,4,7] add_one(grades) Global Space grades id4 Call Frame 0 ERASE WHOLE FRAME Heap Space id4 5 4 7 No lasting changes. What did we accomplish? L 4