Lecture 13. For-Loops

Similar documents
Lecture 13. For-Loops

Iteration and For Loops

Lecture 22. While Loops

Lecture 11: Iteration and For-Loops

Lecture 15. For-Loops

Lecture 20: While Loops (Sections 7.3, 7.4)

CS Prelim 1 Review Fall 2013

CS Lecture 19: Loop invariants

CS 1110: Introduction to Computing Using Python Loop Invariants

isinstance and While Loops

CS Prelim 1 Review Fall 2017

CS Prelim 1 Review Fall 2013

Lecture 7. Memory in Python

CS Prelim 1 Review Fall 2016

Lecture 12. Lists (& Sequences)

Lecture 14. Nested Lists and Dictionaries

PREPARING FOR PRELIM 1

Fundamentals of Programming. Week 1 - Lecture 3: Loops

Lecture 24: Loop Invariants

Lecture 26: Sorting CS 1110 Introduction to Computing Using Python

Lecture 9. Memory and Call Stacks

CS Prelim 1 Review Fall 2018

CS1110 Lab 6 (Mar 17-18, 2015)

CS 1110 Prelim 1 October 4th, 2012

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

SAMS Programming A/B. Lecture #1 Introductions July 3, Mark Stehlik

Lecture 5. Defining Functions

Lecture 3. Functions & Modules

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

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

PREPARING FOR PRELIM 2

Lecture 2: Variables & Assignments

Announcements for This Lecture

CS 1110 Prelim 2 November 14th, 2013

Announcements For This Lecture

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

CS 1110 Prelim 2 November 13th, 2014

Lecture 6: Specifications & Testing

CSE 113 A. Announcements - Lab

Computer Programming

Repetition Structures

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

Lecture 4. Defining Functions

CS150 - Assignment 5 Data For Everyone Due: Wednesday Oct. 16, at the beginning of class

Interlude. Why Object Oriented Programming?

RECURSION (CONTINUED)

Computer Programming

CS 1110 Prelim 1 October 17th, 2013

Announcements For This Lecture

Lecture 10. Daily Puzzle

Lecture 11. Asserts and Error Handling

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

CS Prelim 2 Review Fall 2018

CS Prelim 1 Review Fall 2012

CSE 111 Bio: Program Design I Lecture 13: BLAST, while loops. Bob Sloan (CS) & Rachel Poretsky (Bio) University of Illinois, Chicago October 10, 2017

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

Accelerating Information Technology Innovation

CS1 Lecture 15 Feb. 18, 2019

Lecture 20. Subclasses & Inheritance

RECURSION (CONTINUED)

CMSC201 Computer Science I for Majors

MEIN 50010: Python Flow Control

Lecture 4. Defining Functions

cs1114 REVIEW of details test closed laptop period

CS Prelim 2 Review Fall 2012

Lecture 11. Asserts and Error Handling

Lecture 1. Course Overview, Python Basics

Lecture 7. Scientific Computation

CS1110. Lecture 6: Function calls

ES-2 Lecture: Fitting models to data

Lecture 24. GUI Applications

CMSC 201 Spring 2019 Lab 06 Lists

CS1 Lecture 9 Feb. 5, 2018

CS Prelim 2 Review Fall 2015

INFO Wednesday, September 14, 2016

Last Time. integer/float/string. import math math.sqrt() math.pi. Python Programming, 2/e 2

CS1 Lecture 12 Feb. 11, 2019

} 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 2014

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

CS1210 Lecture 27 Mar. 25, 2019

Announcements for This Lecture

CSE : Python Programming

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

Lecture 25. Sequence Algorithms (Continued)

Lecture 1. Course Overview, Python Basics

Lecture 4. Defining Functions

Flow Control: Branches and loops

CMSC201 Computer Science I for Majors

CS1110 Lab 1 (Jan 27-28, 2015)

CS 1301 CS1 with Robots Summer 2007 Exam 1

CS 1110 Prelim 2 November 12th, 2015

Lecture 24. GUI Applications

Programming for Engineers in Python. Autumn

Loops. Repeat after me

CMSC201 Computer Science I for Majors

Computing with Numbers

Lecture 1. Types, Expressions, & Variables

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

Assignment 3: Due Thursday Feb 26 at 11pm

Transcription:

Lecture 3 For-Loops

Announcements for This Lecture Reading Today: Chapters 8, 0 Thursday: Chapter Prelim, Oct th 7:30-9:00 Material up to TODAY Study guide is posted Review next Wednesday Room/Time are TBA Will cover what is on exam Assignments/Lab A has been graded Pick up in Gates 6 Grades generally good A3 is due on Thursday Will post survey today Survey due next week Lab is on lists/for-loops Due in two weeks But fair game on exam 0/3/7 For Loops

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)""" pass # Stub to be implemented Remember our approach: Outline first; then implement 0/3/7 For Loops 3

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 0/3/7 For Loops 4

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[] return result There is a problem here 0/3/7 For Loops 5

Working with Sequences Sequences are potentially unbounded Number of elements inside them 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 # of elements > # of lines of code? We need a new control structure 0/3/7 For Loops 6

For Loops: Processing Sequences # Print contents of seq x = seq[0] print(x) x = seq[] print(x) x = seq[len(seq)-] print(x) Remember: Cannot program The for-loop: for x in seq: print(x) Key Concepts loop sequence: seq loop variable: x body: print(x) Also called repetend 0/3/7 For Loops 7

For Loops: Processing Sequences The for-loop: for x in seq: print(x) seq has more elts False True put next elt in x print(x) loop sequence: seq loop variable: x body: print(x) To execute the for-loop:. Check if there is a next element of loop sequence. If not, terminate execution 3. Otherwise, put the element in the loop variable 4. Execute all of the body 5. Repeat as long as is true 0/3/7 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)""" # Create a variable to hold result (start at 0) # Add each list element to variable # Return the variable 0/3/7 For Loops 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 for x in thelist: result = result + x return result loop sequence: thelist loop variable: x body: result=result+x 0/3/7 For Loops 0

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 0/3/7 For Loops

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 if it is # Return the variable 0/3/7 For Loops

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+ return result Body 0/3/7 For Loops 3

Modifying the Contents of a List def add_one(thelist): """(Procedure) Adds to every element in the list Precondition: thelist is a list of all numbers (either floats or ints)""" for x in thelist: x = x+ # procedure; no return DOES NOT WORK! 0/3/7 For Loops 4

For Loops and Call Frames def add_one(thelist): """Adds to every elt Pre: thelist is all numb.""" for x in thelist: x = x+ add_one(seq): add_one thelist seq 0 5 4 7 0/3/7 For Loops 5

For Loops and Call Frames def add_one(thelist): """Adds to every elt Pre: thelist is all numb.""" for x in thelist: x = x+ add_one(seq): add_one thelist x 5 seq 0 5 4 7 0/3/7 For Loops 6

For Loops and Call Frames def add_one(thelist): """Adds to every elt Pre: thelist is all numb.""" for x in thelist: x = x+ add_one(seq): add_one thelist x 6 Loop back to line seq 0 5 4 7 Increments x in frame Does not affect folder 0/3/7 For Loops 7

For Loops and Call Frames def add_one(thelist): """Adds to every elt Pre: thelist is all numb.""" for x in thelist: x = x+ add_one(seq): add_one thelist x 4 seq 0 5 4 7 Next element stored in x. Previous calculation lost. 0/3/7 For Loops 8

For Loops and Call Frames def add_one(thelist): """Adds to every elt Pre: thelist is all numb.""" for x in thelist: x = x+ add_one(seq): add_one thelist x 5 Loop back to line seq 0 5 4 7 0/3/7 For Loops 9

For Loops and Call Frames def add_one(thelist): """Adds to every elt Pre: thelist is all numb.""" for x in thelist: x = x+ add_one(seq): add_one thelist x 7 seq 0 5 4 7 Next element stored in x. Previous calculation lost. 0/3/7 For Loops 0

For Loops and Call Frames def add_one(thelist): """Adds to every elt Pre: thelist is all numb.""" for x in thelist: x = x+ add_one(seq): add_one thelist x 8 Loop back to line seq 0 5 4 7 0/3/7 For Loops

For Loops and Call Frames def add_one(thelist): """Adds to every elt Pre: thelist is all numb.""" for x in thelist: x = x+ add_one(seq): add_one thelist x 8 seq 0 5 4 7 Loop is completed. Nothing new put in x. 0/3/7 For Loops

For Loops and Call Frames def add_one(thelist): """Adds to every elt Pre: thelist is all numb.""" for x in thelist: x = x+ add_one(seq): seq 0 5 4 7 No changes to folder 0/3/7 For Loops 3

On The Other Hand def copy_add_one(thelist): """Returns: copy with added to every element Precondition: thelist is a list of all numbers (either floats or ints)""" mycopy = [] # accumulator for x in thelist: x = x+ Accumulator keeps result from being lost mycopy.append(x) # add to end of accumulator return mycopy 0/3/7 For Loops 4

How Can We Modify A List? Never modify loop var! This is an infinite loop: for x in thelist: thelist.append() Need a second sequence How about the positions? thelist = [5,, 7, ] thepos = [0,,, 3] Try this in Python Tutor to see what happens for x in thepos: thelist[x] = thelist[x]+ 0/3/7 For Loops 5

How Can We Modify A List? Never modify loop var! This is an infinite loop: for x in thelist: thelist.append() Need a second sequence How about the positions? thelist = [5,, 7, ] thepos = [0,,, 3] Try this in Python Tutor to see what happens for x in thepos: thelist[x] = thelist[x]+ 0/3/7 For Loops 6

This is the Motivation for Iterators Iterators are objects Contain data like a list But cannot slice them Access data with next() seq id 0 id 5 4 7 Function to get next value Keeps going until end Get an error if go to far alt id id Can convert back & forth? myiter = iter(mylist) mylist = list(myiter) Type/Class conversion 0/3/7 For Loops 7

Iterators and Lists >>> seq = [5, 4, 7] >>> alt = iter(seq) >>> next(alt) 5 seq id 0 id 5 4 7 >>> next(alt) 4 >>> next(alt) 7 alt id id? >>> next(alt) Traceback 0/3/7 For Loops 8

Iterators and For Loops >>> seq = [5, 4, 7] >>> alt = iter(seq) >>> for x in alt: print(x) 5 4 7 Just like looping over the list seq alt id id 0 id 5 4 7 id? 0/3/7 For Loops 9

Iterators and For Loops >>> seq = [5, 4, 7] >>> alt = iter(seq) >>> for x in alt: print(x) 5 4 7 Just like looping over the list seq alt id id 0 id 5 4 7 id But still not safe to modify iterator s list? 0/3/7 For Loops 30

The Range Iterator range(x) Creates an iterator Stores [0,,,x-] But not a list! But try list(range(x)) range(a,b) Stores [a,,b-] range(a,b,n) Stores [a,a+n,,b-] Very versatile tool Great for processing ints total = 0 Accumulator # add the squares of ints # in range..00 to total for x in range(,0): total = total + x*x 0/3/7 For Loops 3

Modifying the Contents of a List def add_one(thelist): """(Procedure) Adds 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]+ # procedure; no return Iterator of list positions (safe) WORKS! 0/3/7 For Loops 3

Important Concept in CS: Doing Things Repeatedly. Process each item in a sequence Compute aggregate statistics for a dataset, such as the mean, median, standard deviation, etc. Send everyone in a Facebook group an appointment time. Perform n trials or get n samples. A4: draw a triangle six times to make a hexagon Run a protein-folding simulation for 0 6 time steps 3. Do something an unknown number of times CUAUV team, vehicle keeps moving until reached its goal 0/3/7 For Loops 33

Important Concept in CS: Doing Things Repeatedly. Process each item in a sequence Compute aggregate statistics for a dataset, for x in sequence: such as the mean, median, standard deviation, process etc. x Send everyone in a Facebook group an appointment time. Perform n trials or get n samples. A4: draw a triangle six times to make for a xhexagon in range(n): Run a protein-folding simulation for 0 do 6 time next steps thing 3. Do something an unknown number of times CUAUV team, vehicle keeps moving until reached its goal Cannot do this yet Impossible w/ Python for 0/3/7 For Loops 34