lecture 11 iteration and for loops
play

Lecture 11: Iteration and For-Loops (Sections 4.2 and 10.3) CS - PowerPoint PPT Presentation

http://www.cs.cornell.edu/courses/cs1110/2018sp Lecture 11: Iteration and For-Loops (Sections 4.2 and 10.3) CS 1110 Introduction to Computing Using Python [E. Andersen, A. Bracy, D. Gries, L. Lee, S. Marschner, C. Van Loan, W. White]


  1. http://www.cs.cornell.edu/courses/cs1110/2018sp Lecture 11: Iteration and For-Loops (Sections 4.2 and 10.3) CS 1110 Introduction to Computing Using Python [E. Andersen, A. Bracy, D. Gries, L. Lee, S. Marschner, C. Van Loan, W. White]

  2. Announcements: Prelim 1 • Rooms: § AA1 — JKZ99999 Baker Laboratory 200 § JL1 — SEZ99999 Rockefeller 201 § SF1 — ZZ999999 Rockefeller 203 • covers material up through today • What to study: A1, A2, Labs 1- 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 cs1110-prof@cornell.edu, and Cc: Jenna Edwards jls478@cornell.edu 2

  3. Announcements • Don’t skip lab! (especially not this lab!) • A2 Due Thursday. Solutions released Friday • A2 must be submitted as a PDF § Convert your files to pdf with Genius Scan https://www.thegrizzlylabs.com/genius-scan/ 3

  4. More Announcements • Lab 6: due in two weeks § Tuesday 3/13 labs: open office hours § Wednesday 3/14 labs: cancelled • Thursday 3/8: optional in-class review session • Tuesday 3/13: no lecture; office hours instead § Olin 155 during class times, Olin 128 in between • A3: released sometime after Prelim 1 4

  5. Advice from Consultants about A1 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

  6. 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

  7. 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

  8. 1 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[1] … Houston, we have a problem return result 8

  9. Working with Sequences • Sequences are potentially unbounded § Number of elements is not fixed § Functions must handle sequences of different lengths § Example : sum([1,2,3]) vs. sum([4,5,6,7,8,9,10]) • 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

  10. For Loops: Processing Sequences • loop sequence: grades • loop variable : x for x in grades: print(x) • body : print(x) To execute the for-loop: 1. Check if there is a “next” element of loop sequence 2. If so: grades has True put next • assign next sequence more elements element in x element to loop variable • Execute all of the body False • Go back to Line 1 print(x) 3. If not, terminate execution 10

  11. 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)""" Accumulator result = 0 variable for x in the_list: • loop sequence: the_list result = result + x • loop variable : x return result • body : result=result+x 11

  12. What gets printed? (Q1) a = 0 a = 0 a = 0 a = 0 for b in [1]: for b in [1, 2]: for b in [1, 2, 3]: for b in [1, 2, 3]: a = a + 1 a = a + 1 a = a + 1 a = b print(a) print(a) print(a) print(a) 12

  13. What gets printed? (A1) a = 0 a = 0 a = 0 a = 0 for b in [1]: for b in [1, 2]: for b in [1, 2, 3]: for b in [1, 2, 3]: a = a + 1 a = a + 1 a = a + 1 a = b print(a) print(a) print(a) print(a) 1 2 3 3 13

  14. What gets printed? (Q2) a = 0 a = 0 a = 0 for b in [1, 2, 3]: b = [1, 2, 3] b = [1, 2, 3] a = a + b for c in b: for c in b: a = a + c a = a + c print(a) print(a) print(b) 14

  15. What gets printed? (A2) a = 0 a = 0 a = 0 for b in [1, 2, 3]: b = [1, 2, 3] b = [1, 2, 3] a = a + b for c in b: for c in b: a = a + c a = a + c print(a) print(a) print(b) 6 6 [1, 2, 3] 15

  16. 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 # Create variable to hold result for x in the_list: # for each element in the list… if type(x) == int: # check if it is an int result = result+1 # add 1 if it is return result # Return the variable 16

  17. 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""" Accumulator variable result = 0 for x in the_list: Loop sequence if type(x) == int: Loop variable result = result+1 Body return result 17

  18. 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! 18

  19. range : a handy counting function! range(x) >>>first_six = list( range(6) ) returns 0,1,…,x-1 >>> print(first_six) [0, 1, 2, 3, 4, 5] range(a,b) >>> second_six = list( range(6,13) ) returns a,…,b-1 >>> print(second_six) [6, 7, 8, 9, 10, 11, 12] Important: range does not return a list à need to convert ranges’ return value into a list 19

  20. range in a for-loop, v1 for num in list(range(10)): line = "The ants go marching "+str(num)+" by "+str(num) for y in list(range(2)): 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….) 20

  21. range in a for-loop, v2 for num in list(range(10)): list(range(1,11)): line = "The ants go marching "+str(num)+" by "+str(num) for y in list(range(2)): 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…. 21

  22. Roses # at our 1 year anniversary my partner gave me a rose # and promised to give me 1 more rose each year thereafter # how many roses will that be?! met_year = 2003 n_years = 75 total_roses = 0 for n_years in list(range(1, n_years+1)): 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!") 22

  23. What gets printed? (Q3) a = 0 a = 0 for b in range(0, 1): for b in range(0, 4): a = a + 1 a = a + 1 print(a) print(a) 23

  24. What gets printed? (A3) a = 0 a = 0 for b in range(0, 1): for b in range(0, 4): a = a + 1 a = a + 1 print(a) print(a) 1 4 24

  25. Modifying the Contents of a List def add_one(the_list): """Adds 1 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]+1 grades = [8,9,10,5,9,10] print("Initial grades are: "+str(grades)) add_one(grades) print("Inflated grades are: "+str(grades)) 25

  26. The Map Function map( ⟨ function ⟩ , ⟨ list ⟩ ) map(f, [a,b,c,d]) • ⟨ function ⟩ takes 1 parameter • Otherwise, error 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 [1, 2, 4] 26

  27. The Filter Function filter( ⟨ Boolean_function ⟩ , ⟨ list ⟩ ) filter(f, [a,b,c]) • ⟨ function ⟩ takes 1 parameter • ⟨ function ⟩ returns a Boolean • Collects elements of ⟨ list ⟩ for a if f(a)==True, which ⟨ Boolean_function ⟩ b if f(b)==True, c if f(c)==True, returns True Important: filter does not return a list à need to convert map’s return value into a list 27 See ints.py to see filter in action

  28. Common For-Loop Mistakes Never modify: (1) the loop sequence (or the list of indices) as you walk through it (2) the loop variable See examples on following slides. 28

  29. For-Loop Mistake #1 (Q) Modifying the loop sequence as you walk through it. b = [1, 2, 3] A: never prints b for a in b: B: [1, 2, 3, 1, 2, 3] b.append(a) C: [1, 2, 3] D: I do not know print b 29

  30. For-Loop Mistake #1 (A) Modifying the loop sequence as you walk through it. b = [1, 2, 3] A: never prints b CORRECT* for a in b: B: [1, 2, 3, 1, 2, 3] b.append(a) C: [1, 2, 3] D: I do not know INFINITE LOOP! * Runs out of memory eventually, print b then probably throws an error. 30

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend