Lecture 11: Iteration and For-Loops

Similar documents
Iteration and For Loops

Lecture 13. For-Loops

Lecture 13. For-Loops

CS Lecture 19: Loop invariants

Lecture 2: Variables & Assignments

CS 1110: Introduction to Computing Using Python Loop Invariants

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

Lecture 24: Loop Invariants

Lecture 20: While Loops (Sections 7.3, 7.4)

Lecture 26: Sorting CS 1110 Introduction to Computing Using Python

isinstance and While Loops

CS 1110: Introduction to Computing Using Python Lists and Sequences

Conditionals & Control Flow

CS1110. Lecture 6: Function calls

Lecture 17: Classes (Chapter 15)

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

Lecture 4: Defining Functions

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

Lecture 10: Lists and Sequences

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

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

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

Lecture 9: Memory in Python

Lecture 19: Subclasses & Inheritance (Chapter 18)

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

Lecture 17: Classes (Chapter 15)

Lecture 5: Strings

CS Prelim 2 Review Fall 2018

CS1110. Lecture 6: Function calls

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

Lecture 6: Specifications & Testing

Lecture 22. While Loops

PREPARING FOR PRELIM 1

Lecture 14. Nested Lists and Dictionaries

CS Prelim 1 Review Fall 2017

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

Homework notes. Homework 2 grades posted on canvas. Homework 3 due tomorrow. Homework 4 posted on canvas. Due Tuesday, Oct. 3

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

Lecture 3: Functions & Modules

Lecture 7. Memory in Python

Lecture 7. Scientific Computation

} 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 1 Review Fall 2013

CS1110 Lab 1 (Jan 27-28, 2015)

CS Prelim 1 Review Fall 2018

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

Lecture 18: Using Classes Effectively (Chapter 16)

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

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

CS 1110 Prelim 2 November 14th, 2013

CS 1110, LAB 3: STRINGS; TESTING

Lecture 12. Lists (& Sequences)

Announcements for This Lecture

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

RECURSION (CONTINUED)

CS Prelim 2 Review Fall 2014

Announcements For This Lecture

Introduction to Scientific Python, CME 193 Jan. 9, web.stanford.edu/~ermartin/teaching/cme193-winter15

Lecture 9. Memory and Call Stacks

RECURSION (CONTINUED)

PREPARING FOR PRELIM 2

CMSC201 Computer Science I for Majors

CSE 115. Introduction to Computer Science I

CS 177 Week 5 Recitation Slides. Loops

Lecture 1. Course Overview, Python Basics

COS 126 Exam Review. Exams overview Example programming exam Example written exam questions (part 1)

CS Prelim 2 Review Fall 2015

CS 1110, LAB 1: PYTHON EXPRESSIONS.

Control Structures 1 / 17

CSE 113 A. Announcements - Lab

CS Prelim 2 Review Fall 2012

CS Prelim 1 Review Fall 2016

Course Overview, Python Basics

Lecture 2. Variables & Assignment

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

CMSC201 Computer Science I for Majors

Announcements For This Lecture

Lecture 1. Course Overview, Python Basics

PREPARING FOR THE FINAL EXAM

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

CMSC 201 Computer Science I for Majors

CS Lecture 26: Subclasses in Event-driven Programs A7 is out! Get started right away you need time to ask questions.

CS/ENGRD 2110 Object-Oriented Programming and Data Structures Spring 2012 Thorsten Joachims

CS1110 Lab 6 (Mar 17-18, 2015)

CS Prelim 2 Review Fall 2017

Lecture 3. Functions & Modules

Designing Loops and General Debug Pre-Defined Functions in C++ CS 16: Solving Problems with Computers I Lecture #6

CS Prelim 1 Review Fall 2013

CS1 Lecture 3 Jan. 22, 2018

Announcements for This Lecture

Last Name: First Name: Cornell NetID, all caps: CS 1110 Regular Prelim 1 Solutions March 2018

Lecture 1. Course Overview Types & Expressions

Lecture 10. Memory in Python

CompSci 101 Introduction to Computer Science

Lecture 5. Defining Functions

Programming for Engineers in Python. Recitation 1

CS 1110 Prelim 2 November 13th, 2014

CS 2316 Exam 1 Spring 2014

CS1 Lecture 3 Jan. 18, 2019

Lecture 1: Introduction, Types & Expressions

Transcription:

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