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

lecture 11 iteration and for loops
SMART_READER_LITE
LIVE PREVIEW

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]


slide-1
SLIDE 1

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]

http://www.cs.cornell.edu/courses/cs1110/2018sp

slide-2
SLIDE 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

slide-3
SLIDE 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

slide-4
SLIDE 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

slide-5
SLIDE 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

slide-6
SLIDE 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

slide-7
SLIDE 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

7

How will we do this?

slide-8
SLIDE 8

1st 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] … return result

8

Houston, we have a problem

slide-9
SLIDE 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

slide-10
SLIDE 10

For Loops: Processing Sequences

for x in grades: print(x)

  • loop sequence: grades
  • loop variable: x
  • body: print(x)

To execute the for-loop: 1. Check if there is a “next” element of loop sequence 2. If so:

  • assign next sequence

element to loop variable

  • Execute all of the body
  • Go back to Line 1

3. If not, terminate execution

grades has more elements put next element in x

True False

print(x)

10

slide-11
SLIDE 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)""" result = 0 for x in the_list: result = result + x return result

11

  • loop sequence: the_list
  • loop variable: x
  • body: result=result+x

Accumulator variable

slide-12
SLIDE 12

What gets printed? (Q1)

a = 0 for b in [1]: a = a + 1 print(a)

12

a = 0 for b in [1, 2]: a = a + 1 print(a) a = 0 for b in [1, 2, 3]: a = a + 1 print(a) a = 0 for b in [1, 2, 3]: a = b print(a)

slide-13
SLIDE 13

What gets printed? (A1)

a = 0 for b in [1]: a = a + 1 print(a)

13

1

a = 0 for b in [1, 2]: a = a + 1 print(a)

2

a = 0 for b in [1, 2, 3]: a = a + 1 print(a)

3

a = 0 for b in [1, 2, 3]: a = b print(a)

3

slide-14
SLIDE 14

What gets printed? (Q2)

a = 0 for b in [1, 2, 3]: a = a + b print(a)

14

a = 0 b = [1, 2, 3] for c in b: a = a + c print(a) a = 0 b = [1, 2, 3] for c in b: a = a + c print(b)

slide-15
SLIDE 15

What gets printed? (A2)

a = 0 for b in [1, 2, 3]: a = a + b print(a)

15

6

a = 0 b = [1, 2, 3] for c in b: a = a + c print(a)

6

a = 0 b = [1, 2, 3] for c in b: a = a + c print(b)

[1, 2, 3]

slide-16
SLIDE 16

# Create variable to hold result # for each element in the list… # check if it is an int # add 1 if it is # Return the variable

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

16

result = 0 for x in the_list: if type(x) == int: result = result+1 return result

slide-17
SLIDE 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"""

17

result = 0 for x in the_list: if type(x) == int: result = result+1 return result

Loop sequence Loop variable Body Accumulator variable

slide-18
SLIDE 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

slide-19
SLIDE 19

range(x) returns 0,1,…,x-1 range(a,b) returns a,…,b-1 Important: range does not return a list à need to convert ranges’ return value into a list

range: a handy counting function!

19

>>>first_six = list(range(6)) >>> print(first_six) [0, 1, 2, 3, 4, 5]

>>> second_six = list(range(6,13))

>>> print(second_six) [6, 7, 8, 9, 10, 11, 12]

slide-20
SLIDE 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

slide-21
SLIDE 21

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")

Ahh, much better…. range in a for-loop, v2

21

list(range(1,11)):

slide-22
SLIDE 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

slide-23
SLIDE 23

What gets printed? (Q3)

a = 0 for b in range(0, 1): a = a + 1 print(a)

23

a = 0 for b in range(0, 4): a = a + 1 print(a)

slide-24
SLIDE 24

What gets printed? (A3)

a = 0 for b in range(0, 1): a = a + 1 print(a)

24

1

a = 0 for b in range(0, 4): a = a + 1 print(a)

4

slide-25
SLIDE 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

slide-26
SLIDE 26

The Map Function

map(⟨function⟩, ⟨list⟩)

  • ⟨function⟩ takes 1 parameter
  • Otherwise, error

Important: map does not return a list à need to convert map’s return value into a list

26

map(f, [a,b,c,d]) f(a), f(b), f(c), f(d)

>>> len_list = list(map(len, ['a', 'bc', 'defg’])) >>> len_list [1, 2, 4]

slide-27
SLIDE 27

The Filter Function

filter(⟨Boolean_function⟩, ⟨list⟩)

  • ⟨function⟩ takes 1 parameter
  • ⟨function⟩ returns a Boolean
  • Collects elements of ⟨list⟩ for

which ⟨Boolean_function⟩ returns 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

27

filter(f, [a,b,c]) a if f(a)==True, b if f(b)==True, c if f(c)==True,

slide-28
SLIDE 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

slide-29
SLIDE 29

For-Loop Mistake #1 (Q)

b = [1, 2, 3] for a in b: b.append(a) print b

29

A: never prints b B: [1, 2, 3, 1, 2, 3] C: [1, 2, 3] D: I do not know

Modifying the loop sequence as you walk through it.

slide-30
SLIDE 30

For-Loop Mistake #1 (A)

b = [1, 2, 3] for a in b: b.append(a) print b

30

A: never prints b B: [1, 2, 3, 1, 2, 3] C: [1, 2, 3] D: I do not know

CORRECT*

INFINITE LOOP!

* Runs out of memory eventually, then probably throws an error.

Modifying the loop sequence as you walk through it.

slide-31
SLIDE 31

For-Loop Mistake #2 (Q)

def add_one(the_list): """Adds 1 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+1 a = [5, 4, 7] add_one(a) print(a)

31

A: [5, 4, 7] B: [5, 4, 7, 5, 4, 7] C: [6, 5, 8] D: Error E: I don’t know What gets printed?

Modifying the loop variable (here: x).

slide-32
SLIDE 32

For-Loop Mistake #2 (A)

def add_one(the_list): """Adds 1 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+1 a = [5, 4, 7] add_one(a) print(a)

32

A: [5, 4, 7] B: [5, 4, 7, 5, 4, 7] C: [6, 5, 8] D: Error E: I don’t know What gets printed?

Modifying the loop variable (here: x).

CORRECT Actually it does not do this!

slide-33
SLIDE 33

Modifying the Loop Variable (1)

def add_one(the_list): """Adds 1 to every elt Pre: the_list is all numb.""" for x in the_list: x = x+1 grades = [5,4,7] add_one(grades)

33

1 2 id4 5 4 7 grades id4 add_one the_list 1 id4 1 2

Heap Space Global Space Call Frame

slide-34
SLIDE 34

def add_one(the_list): """Adds 1 to every elt Pre: the_list is all numb.""" for x in the_list: x = x+1 grades = [5,4,7] add_one(grades)

Modifying the Loop Variable (2)

34

1 2 1 2 id4 5 4 7 grades id4

Heap Space Global Space

add_one the_list 2 id4

Call Frame

x 5

slide-35
SLIDE 35

Modifying the Loop Variable (3)

def add_one(the_list): """Adds 1 to every elt Pre: the_list is all numb.""" for x in the_list: x = x+1 grades = [5,4,7] add_one(grades)

35

1 2

Increments x in frame Does not affect folder

add_one the_list 1 id4 x 6 1 2 id4 5 4 7 grades id4

Heap Space Global Space

Loop back to line 1

Call Frame

slide-36
SLIDE 36

Modifying the Loop Variable (4)

def add_one(the_list): """Adds 1 to every elt Pre: the_list is all numb.""" for x in the_list: x = x+1 grades = [5,4,7] add_one(grades)

36

1 2

Next element stored in x. Previous calculation lost.

add_one the_list 2 id4

Call Frame

x 4 1 2 id4 5 4 7 grades id4

Heap Space Global Space

slide-37
SLIDE 37

Modifying the Loop Variable (5)

def add_one(the_list): """Adds 1 to every elt Pre: the_list is all numb.""" for x in the_list: x = x+1 grades = [5,4,7] add_one(grades)

37

1 2 add_one the_list 1 id4

Call Frame

x 5 1 2 id4 5 4 7 grades id4

Heap Space Global Space

Loop back to line 1

slide-38
SLIDE 38

Modifying the Loop Variable (6)

def add_one(the_list): """Adds 1 to every elt Pre: the_list is all numb.""" for x in the_list: x = x+1 grades = [5,4,7] add_one(grades)

38

1 2

Next element stored in x. Previous calculation lost.

add_one the_list 2 id4

Call Frame

x 7 1 2 id4 5 4 7 grades id4

Heap Space Global Space

slide-39
SLIDE 39

Modifying the Loop Variable (7)

def add_one(the_list): """Adds 1 to every elt Pre: the_list is all numb.""" for x in the_list: x = x+1 grades = [5,4,7] add_one(grades)

39

1 2 add_one the_list 1 id4

Call Frame

x 8 1 2 id4 5 4 7 grades id4

Heap Space Global Space

Loop back to line 1

slide-40
SLIDE 40

Modifying the Loop Variable (8)

def add_one(the_list): """Adds 1 to every elt Pre: the_list is all numb.""" for x in the_list: x = x+1 grades = [5,4,7] add_one(grades)

40

1 2

Loop is completed. Nothing new put in x.

add_one the_list id4

Call Frame

x 8 RETURN NONE 1 2 id4 5 4 7 grades id4

Heap Space Global Space

slide-41
SLIDE 41

Modifying the Loop Variable (9)

def add_one(the_list): """Adds 1 to every elt Pre: the_list is all numb.""" for x in the_list: x = x+1 grades = [5,4,7] add_one(grades)

41

1 2

E R A S E W H O L E F R A M E

No lasting changes. What did we accomplish? L

1 2 id4 5 4 7 grades id4

Heap Space Global Space Call Frame