Iteration and For Loops

Similar documents
Lecture 11: Iteration and For-Loops

Lecture 13. For-Loops

Lecture 13. For-Loops

isinstance and While Loops

CS 1110: Introduction to Computing Using Python Loop Invariants

CS Lecture 19: Loop invariants

CS 1110: Introduction to Computing Using Python Lists and Sequences

Lecture 24: Loop Invariants

Lecture 22. While Loops

Lecture 2: Variables & Assignments

Lecture 7. Scientific Computation

PREPARING FOR PRELIM 1

Lecture 20: While Loops (Sections 7.3, 7.4)

CS 1110, Spring 2018: Prelim 1 study guide Prepared Tuesday March 6, 2018

Lecture 26: Sorting CS 1110 Introduction to Computing Using Python

CS1110. Lecture 6: Function calls

Lecture 14. Nested Lists and Dictionaries

CS 1110, LAB 12: SEQUENCE ALGORITHMS First Name: Last Name: NetID:

CS Lecture 18: Card Tricks. Announcements. Slides by D. Gries, L. Lee, S. Marschner, W. White

PREPARING FOR THE FINAL EXAM

CS Prelim 1 Review Fall 2013

CS1110. Lecture 6: Function calls

Lecture 4: Defining Functions (Ch ) CS 1110 Introduction to Computing Using Python

Lecture 8: Conditionals & Control Flow (Sections ) CS 1110 Introduction to Computing Using Python

Conditionals & Control Flow

Lecture 19: Subclasses & Inheritance (Chapter 18)

Lecture 4: Defining Functions

CS1110 Lab 6 (Mar 17-18, 2015)

Lecture 3: Functions & Modules

CS Prelim 2 Review Fall 2018

Lecture 9. Memory and Call Stacks

CS Lecture 26: Grab Bag. Announcements

Lecture 7. Memory in Python

CS 1110 SPRING 2016: GETTING STARTED (Jan 27-28) First Name: Last Name: NetID:

Lecture 10: Lists and Sequences

CS 1110, LAB 10: ASSERTIONS AND WHILE-LOOPS 1. Preliminaries

CS61A Lecture 16. Amir Kamil UC Berkeley February 27, 2013

CS1110. Lecture 22: Prelim 2 Review Session. Announcements. Processed prelim regrade requests: on the front table.

CS61A Lecture 16. Amir Kamil UC Berkeley February 27, 2013

CS 1110, Spring 2018: Prelim 1 study guide Prepared Tuesday March 6, 2018

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

PREPARING FOR PRELIM 2

Lecture 1. Course Overview Types & Expressions

CS Prelim 1 Review Fall 2017

CS Prelim 1 Review Fall 2018

CS 1110, LAB 1: EXPRESSIONS AND ASSIGNMENTS First Name: Last Name: NetID:

CS 1110 Prelim 1 October 4th, 2012

CS Prelim 1 Review Fall 2013

Sorting and Searching

Lecture 19. Operators and Abstraction

S206E Lecture 19, 5/24/2016, Python an overview

Lecture 12. Lists (& Sequences)

CS Lecture 25: Models, Views, Controllers, and Games. Announcements

Lecture 6: Specifications & Testing

Lecture 18: Using Classes Effectively (Chapter 16)

Accelerating Information Technology Innovation

61A Lecture 4. Monday, September 9

PREPARING FOR THE FINAL EXAM

Announcements for This Lecture

Announcements for this Lecture

Lecture 3: Functions & Modules (Sections ) CS 1110 Introduction to Computing Using Python

ASYMPTOTIC COMPLEXITY

Lecture 17: Classes (Chapter 15)

CS 303E Fall 2011 Exam 2 Solutions and Criteria November 2, Good Luck!

To figure this out we need a more precise understanding of how ML works

CS Prelim 1 Review Fall 2016

Lecture 5: Strings

Course Overview, Python Basics

Lecture 1. Types, Expressions, & Variables

CORRECTNESS ISSUES AND LOOP INVARIANTS

Which of the following expressions has the type int list?

Finding Pi: Applications of Loops, Random Numbers, Booleans CS 8: Introduction to Computer Science, Winter 2018 Lecture #6

CS Prelim 2 Review Fall 2012

CpSc 1111 Lab 4 Part a Flow Control, Branching, and Formatting

CS1 Lecture 3 Jan. 18, 2019

Topic 7: Lists, Dictionaries and Strings

Lecture 9: Memory in Python

Lecture 18. Classes and Types

CS Prelim 2 Review Fall 2014

Course Outline - COMP150. Lectures and Labs

Lecture #12: Immutable and Mutable Data. Last modified: Mon Feb 22 16:33: CS61A: Lecture #12 1

CS1 Lecture 3 Jan. 22, 2018

CS 115 Lecture 4. More Python; testing software. Neil Moore

CSC312 Principles of Programming Languages : Functional Programming Language. Copyright 2006 The McGraw-Hill Companies, Inc.

CS 1110, LAB 3: MODULES AND TESTING First Name: Last Name: NetID:

Lecture 1. Course Overview, Python Basics

Lecture 25. Sequence Algorithms (Continued)

Lecture 10. Daily Puzzle

Lecture 17: Classes (Chapter 15)

} Evaluate the following expressions: 1. int x = 5 / 2 + 2; 2. int x = / 2; 3. int x = 5 / ; 4. double x = 5 / 2.

CS Prelim 2 Review Fall 2017

CS108 Lecture 19: The Python DBAPI

RECURSION (CONTINUED)

RECURSION (CONTINUED)

Lecture 7: Objects (Chapter 15) CS 1110 Introduction to Computing Using Python

CS 1110 Prelim 2 November 14th, 2013

Lecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18

6.01, Spring Semester, 2008 Assignment 3, Issued: Tuesday, February 19 1

Introduction to Concepts in Functional Programming. CS16: Introduction to Data Structures & Algorithms Spring 2017

CS 1110 Prelim 2 November 6th, 2012

Transcription:

CS 1110: Introduction to Computing Using Python Lecture 11 Iteration and For Loops [Andersen, Gries, Lee, Marschner, Van Loan, White]

Rooms: Announcements: Prelim 1 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

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

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

strings: immutable sequences of characters Tuples tuple generalizes pair, triple, quadruple, tuples: immutable sequences of any objects Tuples fall between strings and lists lists: mutable sequences of any objects write them with just commas: 42, 4.0, x often enclosed in parentheses: (42, 4.0, x ) Conventionally use lists for: long sequences homogeneous sequences variable length sequences Conventionally use tuples for: short sequences heterogeneous sequences fixed length sequences Iteration and For Loops 5

Returning multiple values 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) Iteration and For Loops 6

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

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

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 There is a problem here Iteration and For Loops 9

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

The Map Function map( function, list ) Function has to have exactly 1 parameter Otherwise, get an error Returns a new list map(f, x) [f(x[0]), f(x[1]),, f(x[n 1])] calls the function f once for each item map(len, ['a', 'bc', 'defg']) returns [1, 2, 4] Iteration and For Loops 11

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 filter(f, x) [f(x[0]), f(x[1]),, f(x[n 1])] calls the function f once for each item Iteration and For Loops 12

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

For Loops The for-loop: for x in seq: print x seq has more elements False True put next element in x 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 Iteration and For Loops 14

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

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 Accumulator for x in thelist: result = result + x return result variable loop sequence: thelist loop variable: x body: result=result+x Iteration and For Loops 16

What gets printed? a = 0 for b in [1]: a = a + 1 prints 1 print a Iteration and For Loops 17

What gets printed? a = 0 for b in [1, 2]: a = a + 1 prints 2 print a Iteration and For Loops 18

What gets printed? a = 0 for b in [1, 2, 3]: a = a + 1 prints 3 print a Iteration and For Loops 19

What gets printed? a = 0 for b in [1, 2, 3]: a = b prints 3 print a Iteration and For Loops 20

What gets printed? a = 0 for b in [1, 2, 3]: a = a + b prints 6 print a Iteration and For Loops 21

What gets printed? a = 0 b = [1, 2, 3] for c in b: a = a + c prints 6 print a Iteration and For Loops 22

What gets printed? a = 0 b = [1, 2, 3] for c in b: a = a + c prints [1, 2, 3] print b Iteration and For Loops 23

What gets printed? b = [1, 2, 3] for a in b: b.append(a) INFINITE LOOP! A: never prints b B: [1, 2, 3, 1, 2, 3] C: [1, 2, 3] D: I do not know CORRECT* print b * Runs out of memory eventually, then probably throws an error. Iteration and For Loops 24

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 sounds kind of like filter Iteration and For Loops 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""" result = 0 for x in thelist: if type(x) == int: result = result+1 return result Body Iteration and For Loops 26

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: What gets printed? x = x+1 >>> a = [5, 4, 7] >>> add_one(a) >>> a A: [5, 4, 7] B: [5, 4, 7, 5, 4, 7] C: [6, 5, 8] D: Error E: I don t know Iteration and For Loops 27

Modifying the Contents of a List 1 2 def add_one(thelist): add_one(seq): """Adds 1 to every elt add_one Pre: thelist is all numb.""" for x in thelist: x = x+1 thelist 1 seq 0 1 2 5 4 7 Iteration and For Loops 28

Modifying the Contents of a List 1 def add_one(thelist): add_one(seq): """Adds 1 to every elt add_one Pre: thelist is all numb.""" for x in thelist: x = x+1 thelist 2 x 5 2 seq 0 1 2 5 4 7 Iteration and For Loops 29

Modifying the Contents of a List 1 def add_one(thelist): add_one(seq): """Adds 1 to every elt add_one Pre: thelist is all numb.""" for x in thelist: x = x+1 thelist 2 x 6 Loop back to line 1 1 seq 0 1 2 5 4 7 Increments x in frame Does not affect folder Iteration and For Loops 30

Modifying the Contents of a List 1 def add_one(thelist): add_one(seq): """Adds 1 to every elt add_one Pre: thelist is all numb.""" for x in thelist: x = x+1 thelist 2 x 4 2 seq 0 1 2 5 4 7 Next element stored in x. Previous calculation lost. Iteration and For Loops 31

Modifying the Contents of a List 1 def add_one(thelist): add_one(seq): """Adds 1 to every elt add_one Pre: thelist is all numb.""" for x in thelist: x = x+1 thelist 2 x 5 Loop back to line 1 1 seq 0 1 2 5 4 7 Iteration and For Loops 32

Modifying the Contents of a List 1 def add_one(thelist): add_one(seq): """Adds 1 to every elt add_one Pre: thelist is all numb.""" for x in thelist: x = x+1 thelist 2 x 7 2 seq 0 1 2 5 4 7 Next element stored in x. Previous calculation lost. Iteration and For Loops 33

Modifying the Contents of a List 1 def add_one(thelist): add_one(seq): """Adds 1 to every elt add_one Pre: thelist is all numb.""" for x in thelist: x = x+1 thelist 2 x 8 Loop back to line 1 1 seq 0 1 2 5 4 7 Iteration and For Loops 34

1 Modifying the Contents of a List def add_one(thelist): add_one(seq): """Adds 1 to every elt add_one Pre: thelist is all numb.""" for x in thelist: x = x+1 thelist 2 x 8 seq 0 1 2 5 4 7 Loop is completed. Nothing new put in x. Iteration and For Loops 35

1 2 Modifying the Contents of a List def add_one(thelist): add_one(seq): """Adds 1 to every elt Pre: thelist is all numb.""" for x in thelist: x = x+1 seq 0 1 2 5 4 7 No changes to folder Iteration and For Loops 36

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: What gets printed? x = x+1 A: [1, 2, 3] CORRECT B: [1, 2, 3, 1, 2, 3] >>> a = [1, 2, 3] C: [2, 3, 4] >>> add_one(a) D: Error E: I don t know >>> a Iteration and For Loops 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 DOES NOT WORK! >>> a = [1, 2, 3] >>> add_one(a) >>> a Iteration and For Loops 38

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 Accumulator keeps result from being lost mycopy.append(x) # add to end of accumulator return mycopy Iteration and For Loops 39

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 Iteration and For Loops 40

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

What gets printed? a = 0 for b in range(0, 1): a = a + 1 prints 1 print a Iteration and For Loops 42

What gets printed? a = 0 for b in range(0, 4): a = a + 1 prints 4 print a Iteration and For Loops 43

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): WORKS! thelist[k] = thelist[k]+1 # procedure; no return Iteration and For Loops 44