Iteration and For Loops [Andersen, Gries, Lee, Marschner, Van Loan, - - PowerPoint PPT Presentation

iteration and for loops
SMART_READER_LITE
LIVE PREVIEW

Iteration and For Loops [Andersen, Gries, Lee, Marschner, Van Loan, - - PowerPoint PPT Presentation

CS 1110: Introduction to Computing Using Python Lecture 11 Iteration and For Loops [Andersen, Gries, Lee, Marschner, Van Loan, White] Announcements: Prelim 1 Rooms: aa200 jjm200 Baker Laboratory 200 jjm201 sge200


slide-1
SLIDE 1

Iteration and For Loops

Lecture 11

CS 1110:

Introduction to Computing Using Python

[Andersen, Gries, Lee, Marschner, Van Loan, White]

slide-2
SLIDE 2

Announcements: Prelim 1

  • Rooms:
  • aa200 – jjm200

Baker Laboratory 200

  • jjm201 – sge200

Rockefeller 201

  • sge201 – zz200

Rockefeller 203

  • covers material up through today

no assert, try-except

  • What to study: A1, A2, Labs 1-6, old exam questions:
  • Fall 2016, 2015, 2014 call-frame/diagram questions need to

be converted to our notation.

  • Prelim will probably be closer in style to Spring 2013-

2014 than more recent exams

Iteration and For Loops 2 3/7/17

slide-3
SLIDE 3

Prelim 1: Things that are not “fair game”

  • Prelim 1 fall 2016: ignore 3b (too lecture-dependent)
  • Prelim 1 spring 2016: ignore 1, 3, 6.
  • 4 is OK if you ignore the "if name == ..." line, and just

assume all that stuff is script code to be run

  • Prelim 1 fall 2015: ignore 4(a) – solutions have typos
  • 4(c) not fair game (asserts)
  • Prelim 1 spring 2015: ignore 2(b), 3(b), 5
  • For 1(b), imagine that variable s contains some arbitrary,

unknown string (we didn't formally cover raw_input)

  • Prelim 1 fall 2014: ignore 2(e), 4(a)
  • Prelim 1 spring 2013: question 6: change cunittest2 to cornelltest

Iteration and For Loops 3 3/7/17

slide-4
SLIDE 4

More Announcements

  • A2: due today. Solutions released Thursday.
  • Lab 6: due in two weeks
  • Tuesday 3/14 labs: open office hours
  • Wednesday 3/15 labs: cancelled
  • Thursday 3/9: optional in-class review session
  • Tuesday 3/14: no lecture; office hours instead
  • Olin 155 during class times, Carpenter in between
  • A3: released sometime after Prelim 1

Iteration and For Loops 4 3/7/17

slide-5
SLIDE 5

Tuples

  • Tuples fall between strings and lists
  • write them with just commas: 42, 4.0, ‘x’
  • often enclosed in parentheses: (42, 4.0, ‘x’)

strings: immutable sequences of characters lists: mutable sequences of any objects tuples: immutable sequences of any objects

Conventionally use lists for:

  • long sequences
  • homogeneous sequences
  • variable length sequences

Conventionally use tuples for:

  • short sequences
  • heterogeneous sequences
  • fixed length sequences

“tuple” generalizes “pair,” “triple,” “quadruple,” …

Iteration and For Loops 5 3/7/17

slide-6
SLIDE 6

Returning multiple values

Iteration and For Loops 6

  • Can use lists/tuples to

return multiple values def div_rem(x,y): 1 return (x/y, x%y) >>> div_rem(3,2) (1 ,1)

3/7/17

slide-7
SLIDE 7

Example: Summing the Elements of a List

def sum(thelist): """Returns: the sum of all elements in thelist Precondition: thelist is a list of all numbers (either floats or ints)"""

Iteration and For Loops 7 3/7/17

slide-8
SLIDE 8

Example: Summing the Elements of a List

def sum(thelist): """Returns: the sum of all elements in thelist Precondition: thelist 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

Iteration and For Loops 8 3/7/17

slide-9
SLIDE 9

Example: Summing the Elements of a List

def sum(thelist): """Returns: the sum of all elements in thelist Precondition: thelist is a list of all numbers (either floats or ints)""" result = 0 result = result + thelist[0] result = result + thelist[1] … return result

Iteration and For Loops 9

There is a problem here

3/7/17

slide-10
SLIDE 10

Working with Sequences

  • Sequences are potentially unbounded
  • Number of elements inside them 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 # of elements > # of lines of code?
  • We need a new approach

Iteration and For Loops 10 3/7/17

slide-11
SLIDE 11

The Map Function

  • map(⟨function⟩, ⟨list⟩)
  • Function has to have

exactly 1 parameter

  • Otherwise, get an error
  • Returns a new list

Iteration and For Loops 11

map(f, x) [f(x[0]), f(x[1]), …, f(x[n–1])]

calls the function f

  • nce for each item

map(len, ['a', 'bc', 'defg']) returns [1, 2, 4]

3/7/17

slide-12
SLIDE 12

The Filter Function

  • filter(⟨Boolean_function⟩,

⟨list⟩)

  • Function must:
  • have exactly 1 parameter
  • return a Boolean
  • Returns a new list
  • Returns elements of ⟨list⟩

for which ⟨Boolean_function⟩, returns True

Iteration and For Loops 12

filter(f, x) [f(x[0]), f(x[1]), …, f(x[n–1])]

calls the function f

  • nce for each item

3/7/17

slide-13
SLIDE 13

For Loops: Processing Sequences

# Print contents of seq x = seq[0] print x x = seq[1] print x … x = seq[len(seq)-1] print x

The for-loop: for x in seq: print x

  • Key Concepts
  • loop sequence: seq
  • loop variable: x
  • body: print x
  • Also called repetend

Iteration and For Loops 13 3/7/17

slide-14
SLIDE 14

For Loops

The for-loop:

for x in seq: print x

  • loop sequence: seq
  • loop variable: x
  • body: print x

To execute the for-loop: 1. Check if there is a “next” element of loop sequence 2. If not, terminate execution 3. Otherwise, assign element to the loop variable 4. Execute all of the body 5. Repeat as long as 1 is true

seq has more elements put next element in x

True False

print x

Iteration and For Loops 14 3/7/17

slide-15
SLIDE 15

Example: Summing the Elements of a List

def sum(thelist): """Returns: the sum of all elements in thelist Precondition: thelist 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

Iteration and For Loops 15 3/7/17

slide-16
SLIDE 16

Example: Summing the Elements of a List

def sum(thelist): """Returns: the sum of all elements in thelist Precondition: thelist is a list of all numbers (either floats or ints)""" result = 0 for x in thelist: result = result + x return result

Iteration and For Loops 16

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

Accumulator variable

3/7/17

slide-17
SLIDE 17

What gets printed?

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

3/7/17 Iteration and For Loops 17

prints 1

slide-18
SLIDE 18

What gets printed?

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

3/7/17 Iteration and For Loops 18

prints 2

slide-19
SLIDE 19

What gets printed?

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

3/7/17 Iteration and For Loops 19

prints 3

slide-20
SLIDE 20

What gets printed?

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

3/7/17 Iteration and For Loops 20

prints 3

slide-21
SLIDE 21

What gets printed?

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

3/7/17 Iteration and For Loops 21

prints 6

slide-22
SLIDE 22

What gets printed?

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

3/7/17 Iteration and For Loops 22

prints 6

slide-23
SLIDE 23

What gets printed?

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

3/7/17 Iteration and For Loops 23

prints [1, 2, 3]

slide-24
SLIDE 24

What gets printed?

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

3/7/17 Iteration and For Loops 24

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.

slide-25
SLIDE 25

For Loops and Conditionals

def num_ints(thelist): """Returns: the number of ints in thelist Precondition: thelist is a list of any mix of types""" # Create a variable to hold result (start at 0) # for each element in the list… # check if it is an int # add 1 if it is # Return the variable

Iteration and For Loops 25 3/7/17

sounds kind of like filter

slide-26
SLIDE 26

For Loops and Conditionals

def num_ints(thelist): """Returns: the number of ints in thelist Precondition: thelist is a list of any mix of types""" result = 0 for x in thelist: if type(x) == int: result = result+1 return result

Iteration and For Loops 26

Body

3/7/17

slide-27
SLIDE 27

Modifying the Contents of a List

def add_one(thelist): """(Procedure) Adds 1 to every element in the list Precondition: thelist is a list of all numbers (either floats or ints)""" for x in thelist: x = x+1 >>> a = [5, 4, 7] >>> add_one(a) >>> a

Iteration and For Loops 27 3/7/17

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?

slide-28
SLIDE 28

Modifying the Contents of a List

def add_one(thelist): """Adds 1 to every elt Pre: thelist is all numb.""" for x in thelist: x = x+1 add_one(seq):

Iteration and For Loops 28

1 2 id4 5 4 7 seq id4 add_one thelist 1 id4 1 2

3/7/17

slide-29
SLIDE 29

Modifying the Contents of a List

def add_one(thelist): """Adds 1 to every elt Pre: thelist is all numb.""" for x in thelist: x = x+1 add_one(seq):

Iteration and For Loops 29

1 2 id4 5 4 7 seq id4 add_one thelist 2 id4 1 2 x 5

3/7/17

slide-30
SLIDE 30

Modifying the Contents of a List

def add_one(thelist): """Adds 1 to every elt Pre: thelist is all numb.""" for x in thelist: x = x+1 add_one(seq):

Iteration and For Loops 30

1 2 id4 5 4 7 seq id4 add_one thelist 1 id4 1 2 x 6

Increments x in frame Does not affect folder Loop back to line 1

3/7/17

slide-31
SLIDE 31

Modifying the Contents of a List

def add_one(thelist): """Adds 1 to every elt Pre: thelist is all numb.""" for x in thelist: x = x+1 add_one(seq):

Iteration and For Loops 31

1 2 id4 5 4 7 seq id4 add_one thelist 2 id4 1 2 x 4

Next element stored in x. Previous calculation lost.

3/7/17

slide-32
SLIDE 32

Modifying the Contents of a List

def add_one(thelist): """Adds 1 to every elt Pre: thelist is all numb.""" for x in thelist: x = x+1 add_one(seq):

Iteration and For Loops 32

1 2 id4 5 4 7 seq id4 add_one thelist 1 id4 1 2 x 5

Loop back to line 1

3/7/17

slide-33
SLIDE 33

Modifying the Contents of a List

def add_one(thelist): """Adds 1 to every elt Pre: thelist is all numb.""" for x in thelist: x = x+1 add_one(seq):

Iteration and For Loops 33

1 2 id4 5 4 7 seq id4 add_one thelist 2 id4 1 2 x 7

Next element stored in x. Previous calculation lost.

3/7/17

slide-34
SLIDE 34

Modifying the Contents of a List

def add_one(thelist): """Adds 1 to every elt Pre: thelist is all numb.""" for x in thelist: x = x+1 add_one(seq):

Iteration and For Loops 34

1 2 id4 5 4 7 seq id4 add_one thelist 1 id4 1 2 x 8

Loop back to line 1

3/7/17

slide-35
SLIDE 35

Modifying the Contents of a List

def add_one(thelist): """Adds 1 to every elt Pre: thelist is all numb.""" for x in thelist: x = x+1 add_one(seq):

Iteration and For Loops 35

1 2 id4 5 4 7 seq id4 add_one thelist id4 1 2 x 8

Loop is completed. Nothing new put in x.

3/7/17

slide-36
SLIDE 36

Modifying the Contents of a List

def add_one(thelist): """Adds 1 to every elt Pre: thelist is all numb.""" for x in thelist: x = x+1 add_one(seq):

Iteration and For Loops 36

1 2 id4 5 4 7 seq id4 1 2

No changes to folder

3/7/17

slide-37
SLIDE 37

Modifying the Contents of a List

def add_one(thelist): """(Procedure) Adds 1 to every element in the list Precondition: thelist is a list of all numbers (either floats or ints)""" for x in thelist: x = x+1 >>> a = [1, 2, 3] >>> add_one(a) >>> a

Iteration and For Loops 37 3/7/17

A: [1, 2, 3] B: [1, 2, 3, 1, 2, 3] C: [2, 3, 4] D: Error E: I don’t know

CORRECT

What gets printed?

slide-38
SLIDE 38

Modifying the Contents of a List

def add_one(thelist): """(Procedure) Adds 1 to every element in the list Precondition: thelist is a list of all numbers (either floats or ints)""" for x in thelist: x = x+1 >>> a = [1, 2, 3] >>> add_one(a) >>> a

Iteration and For Loops 38 3/7/17

DOES NOT WORK!

slide-39
SLIDE 39

On The Other Hand

def copy_add_one(thelist): """Returns: copy with 1 added to every element Precondition: thelist is a list of all numbers (either floats or ints)""" mycopy = [] # accumulator for x in thelist: x = x+1 mycopy.append(x) # add to end of accumulator return mycopy

Iteration and For Loops 39

Accumulator keeps result from being lost

3/7/17

slide-40
SLIDE 40

Range Function

  • range(x):

returns a list of ints from 0 to x-1

  • range(a,b):

returns a list of ints from a to b-1

3/7/17 Iteration and For Loops 40

slide-41
SLIDE 41

For Loops: Processing Ranges of Integers

  • For each x in the range

2..200, add x*x to total total = 0 # add the squares of ints # in range 2..200 to total total = total + 2*2 total = total + 3*3 … total = total + 200*200

total = 0 for x in range(2,201): total = total + x*x

Iteration and For Loops 41 3/7/17

slide-42
SLIDE 42

What gets printed?

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

3/7/17 Iteration and For Loops 42

prints 1

slide-43
SLIDE 43

What gets printed?

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

3/7/17 Iteration and For Loops 43

prints 4

slide-44
SLIDE 44

Modifying the Contents of a List

def add_one(thelist): """(Procedure) Adds 1 to every element in the list Precondition: thelist is a list of all numbers (either floats or ints)""" size = len(thelist) for k in range(size): thelist[k] = thelist[k]+1 # procedure; no return

Iteration and For Loops 44

WORKS!

3/7/17