640 likes | 862 Vues
IST380. Loops got you going in circles?. Nest them!. infinitely nested structure…. 3/10 2day == 2d data. 3/17 spring break!. 3/24 no class. from finitely nested loops. 3/31 we meet again…. nested loops == 2d data. Schedule. User input.
E N D
IST380 • Loops got you going in circles? • Nest them! infinitely nested structure… • 3/10 2day == 2d data • 3/17 spring break! • 3/24 no class from finitely nested loops • 3/31 we meet again… • nested loops == 2d data • Schedule
User input meters = raw_input('How many m? ') cm = meters * 100 print'That is', cm, 'cm.' You know you've become a programmer when you ask yourself… What will Python think? I think I like these units better than light years per year!
User input meters = raw_input('How many m? ') cm = meters * 100 print'That is', cm, 'cm.' What will Python think? I think I like these units better than light years per year!
User input meters = raw_input('How many m? ') cm = meters * 100 print'That is', cm, 'cm.' raw_inputALWAYSreturns a string– no matter what has been typed! What will Python think? I think I like these units better than light years per year!
Fix #1: convert to the right type meters_str = raw_input('How many m? ') meters = float( meters_str ) cm = meters * 100 print'That is', cm, 'cm.' 4200.0 '42' 42.0 name: meters_str type: string name: meters type: float name: cm type: float
Fix #2: use input meters = input('How many m? ') cm = meters * 100 print'That is', cm, 'cm.' input interprets its input raw_input always returns a string I always use input -- but don't "quote" me on that.
hw6pr1: T. T. Securities (TTS) Analyzes a sequence of stock prices day 0 day 1 day 2 day 5 day 6 day 7 day 3 day 4 L = [ 40, 80, 10, 30, 27, 52, 5, 15 ] (0) Input a new list (1) Print the current list (2) Find the average price (3) Find the standard deviation (4) Find the min and its day (5) Find the max and its day (6) Your TTS investment plan (9) Quit Enter your choice: The menu to implement:
hw6pr1: T. T. Securities (TTS) Analyzes a sequence of stock prices day 0 day 1 day 2 day 5 day 6 day 7 day 3 day 4 L = [ 40, 80, 10, 30, 27, 52, 5, 15 ] Loop Review! (0) Input a new list (1) Print the current list (2) Find the average price (3) Find the standard deviation (4) Find the min and its day (5) Find the max and its day (6) Your TTS investment plan (9) Quit Enter your choice: The menu to implement:
A larger application def menu(): """ prints our menu of options """ print"(1) Input a new list of numbers" print"(2) I will divine the next element" print"(9) Quit" def main(): """ handles user input for our menu """ whileTrue: menu() uc = input('Which option? ') Calls a helper function Perhaps ucthe reason for this?
def main(): """ handles user input for our menu """ L = [2,12,22,32] # a starting list whileTrue: menu() # print menu uc = input('Which option? ') if uc == 9: elifuc == 1: elifuc == 2: (9) Quit! (1) Get new list (2) other…
def main(): """ handles user input for our menu """ L = [2,12,22,32] # a starting list whileTrue: menu() # print menu uc = input('Which option? ') if uc == 9: elifuc == 1: elifuc == 2: break exits the loop (9) Quit! use input to get a new L (1) Get new list other functions, as needed (2) other…
Functions you'll write All use loops… def average( L ) Menu def stdev( L ) (0) Input a new list (1) Print the current list (2) Find the average price (3) Find the standard deviation (4) Find the min and its day (5) Find the max and its day (6) Your TTS investment plan (9) Quit Enter your choice: (L[i] - Lav)2 i len(L) def minday( L ) def maxday( L ) webbrowser.open_new_tab(url)
Min price Just call min ? What's the idea for finding the smallest (minimum) price? day 0 day 1 day 2 day 5 day 6 day 7 day 3 day 4 L = [ 40, 80, 10, 30, 27, 52, 5, 15 ] m = m is the "min so far" track the value of the minimum so far as you loop over L
Min price vs. min day day 0 day 1 day 2 day 5 day 6 day 7 day 3 day 4 L = [ 40, 80, 10, 30, 27, 52, 5, 15 ] m = 40 m = 10 m = 5 5 is returned defminprice( L ): m = L[0] for x in L: ifx < m: m = x returnm What about the day of the minimum price?
L return the index of L's minimum. minday >>> minday( [9, 8, 5, 7, 42] ) 2 index 0 1 2 3 4 defminday( L ): m = L[0] mndy= 0 for : if < m: m = return mndy How do we loop through the INDEX of each element? How do we ensure m keeps track of the minimum? How and where should we update mndy? index-based loop
L return the index of L's minimum. minday >>> minday( [9, 8, 5, 7, 42] ) 2 index 0 1 2 3 4 defminday( L ): m = L[0] mndy= 0 day = 0 for x in L: if x < m: m = x mndy = day day += 1 return mndy Create a "counter" that will keep track of the current day. IF we find a smaller min, save which day it was in mndy Regardless, we add 1 to day so that we're keeping track! element-based loop
personal motivation for TT securities… LightPath, Summer 1999 ~ wedding gift…
Why it's called a brokerage LightPath, Fall 2013
T. T. Securities (0) Input a new list (1) Print the current list (2) Find the average price (3) Find the standard deviation (4) Find the min and its day (5) Find the max and its day (6) Your TTS investment plan (9) Quit Enter your choice: Software side … Hardware side… Investment analysis for the 21st century … and beyond!
T. T. Securities (0) Input a new list (1) Print the current list (2) Find the average price (3) Find the standard deviation (4) Find the min and its day (5) Find the max and its day (6) Your TTS investment plan (9) Quit Enter your choice: Software side … Hardware side… Investment analysis for the 21st century … and beyond!
T. T. Securities (0) Input a new list (1) Print the current list (2) Find the average price (3) Find the standard deviation (4) Find the min and its day (5) Find the max and its day (6) Your TTS investment plan (9) Quit Enter your choice: Back to the future Software side … Hardware side… Investment analysis for the 21st century … and beyond!
The TTS advantage! L = [ 40, 80, 10, 30, 27, 52, 5, 15 ] Your stock's prices: What is the best TTS investment strategy here? Day Price 0 40.0 1 80.0 2 10.0 3 30.0 4 27.0 5 52.0 6 5.0 7 15.0 To be realistic, however (for our VC backers and the SEC), you may only sell afteryou buy.
In CS, rules rule! Reference Pointer id L = [5,42,'hi'] s = 'hi' 'hi' 'hi' 42 5 L s L[0] L[1] L[2] (1a) Numbers and strings are handled "by value" (1b) Lists are handled "by reference"
In CS, rules rule! Reference Pointer id L = [5,42,'hi'] s = 'hi' 'hi' 'hi' 42 5 L s L[0] L[1] L[2] (1a) Numbers and strings are handled "by value" (1b) Lists are handled "by reference" The contents of the variable's "box" in memory are copied. (2) Inputs pass to functions "by value" 7 copy of fav 7 fav f( fav ) fav
Reference vs. Value Python's two methods for handling data L = [5,42,'hi'] s = 'hi' Reference Pointer id Whee! 'hi' 'hi' s 42 5 L L[0] L[1] L[2] Lists are handled by reference (the variables really hold a memory address) Primitive data and strings are handled by value: imagine they hold the data
Python functions: pass by value defconform(fav) fav = 42 return fav fav defmain() print " Welcome! " fav = 7 conform(fav) print " My favorite # is", fav 7 fav But what if the underlined part were absent… ?
Python functions: pass by value 42 defconform(fav) fav = 42 return fav 7 fav copy of fav "pass by value" means the contents of fav are copied to fav defmain() print " Welcome! " fav = 7 conform(fav) print " My favorite # is", fav 7 fav But what if the underlined part were absent… ?
Python functions: pass by value defconform(fav) fav[0] = 42 fav[1] = 42 return fav fav 7 11 defmain() print " Welcome! " fav = [7,11] conform(fav) print " My favorite #s: ", fav fav[0] fav[1] fav But what if the underlined part were absent… ?
Python functions: pass by value defconform(fav) fav[0] = 42 fav[1] = 42 return fav fav 7 11 defmain() print " Welcome! " fav = [7,11] conform(fav) print " My favorite #s: ", fav fav[0] fav[1] fav But what if the underlined part were absent… ?
Lists are Mutable You can change the contents of lists in functions that take those lists as input. - Lists are MUTABLE objects Those changes will be visible everywhere. One rule rules them all: pass-by-value Numbers, strings, etc. are IMMUTABLE – they can't be changed, only reassigned.
Differing approaches to rules … Engineers Physicists different worldviews… Mathematicians CS?
"the rules" Engineersbelieve equations approximate reality; Safety margins! Grand Canyon Skywalk
Engineers believe equations approximate reality; Physicists believe reality approximates equations… Image forensics' verdict: Fake! Not a parabola, so not a real shot! http://www.youtube.com/watch?feature=player_embedded&v=WbaH52JI3So http://www.fourandsix.com/blog/2011/8/29/seriously-amazing-beer-pong-shots.html
Engineers believe equations approximate reality; Physicists believe reality approximates equations… Mathematicians don't care either way! A solid sphere can be split into 5 parts and rigidly reassembled into two spheres the same size as the original Banach-Tarski paradox Banach-Tarski XKCD the parts are "mist"
Engineers believe equations approximate reality; Physicists believe reality approximates equations… Mathematicians don't care either way! why settle for gears, when you could have fractalgears? In CS? Don't like reality?Build a new one!
Engineers believe equations approximate reality; Physicists believe reality approximates equations… Mathematics reasons about structuralrules… … and CS reasons about proceduralones. for lists variables while Axioms arithmetic operations Definitions if/else proofs programs Insights, tools, truths Insights, tools, algorithms math worldview CS worldview
2D data! One rule rules them all: everything's a list!
Lists ~ 2D data A = [ 42, 75, 70 ] 70 42 75 int int int list A One rule rules them all: everything's a list! 1D lists are familiar – but lists can hold ANY kind of data – including lists!
Lists ~2D data A = [ [1,2,3,4], [5,6], [7,8,9,10,11] ] 2 1 4 3 list list A[0][1] A[0][0] A[0][3] A[0] A ? 6 5 list A[1][1] A[1][0] A[1] 8 7 10 9 11 list A[2] A[2][0] A[2][1] A[2][2] A[2][3] A[2][4] Where's 3? len(A[0]) len(A) Replace 10 with 42.
Rectangular 2D data A = [ [1,2,3,4], [5,6,7,8], [9,0,1,2] ] 1 2 3 4 list list A[0] A A[0][0] 7 8 5 6 list A[1] 9 0 1 2 list A[2] A[2][3] To try… What is A[1][2]? What does each component of A[1][2] mean ? How many rows does A have, in general ? How many columns does A have, in general ?
Try it… A = [ [1, 2, 3, 4], [5, 6, 7, 8], [9,10,11,12] ] Starting with the 2d array A shown here, what are the values in A after running this code? A Before def mystery(A): """ what happens to A ? """ NROWS = len(A) NCOLS = len(A[0]) for row in range( 0,NROWS ): for col in range( 0,NCOLS ): if row == col: A[row][col] = 42 else: A[row][col] += 1 1 2 3 4 5 6 7 8 9 10 11 12 row 0 row 1 row 2 col 0 col 1 col 2 col 3 A After What are the resulting values in A?
hw6pr2: John Conway's Game of Life red cells are "alive" John Conway • Are there a few simple rules that could give rise to intricate, complex phenomena… • They need to be local • Chemistry ~ life! How? white cells are empty
hw6pr2: John Conway's Game of Life Grid World Evolutionary rules red cells are "alive" • Everything depends on a cell's eight neighbors • Exactly 3 neighbors give birth to a new, live cell. • Exactly 2 or 3 neighbors keep an existing cell alive. Only 3 rules • Any other # of neighbors and the central cell dies… white cells are empty
Lab Problem: Conway's Game of Life Grid World Evolutionary rules red cells are "alive" • Everything depends on a cell's eight neighbors • Exactly 3 neighbors give birth to a new, live cell. • Exactly 2 or 3 neighbors keep an existing cell alive. • Any other # of neighbors and the central cell dies… white cells are empty
Lab Problem: Conway's Game of Life Grid World Evolutionary rules red cells are "alive" • Everything depends on a cell's eight neighbors • Exactly 3 neighbors give birth to a new, live cell. • Exactly 2 or 3 neighbors keep an existing cell alive. • Any other # of neighbors and the central cell dies… white cells are empty
Lab Problem: Conway's Game of Life Grid World Evolutionary rules red cells are alive • Everything depends on a cell's eight neighbors • Exactly 3 neighbors give birth to a new, live cell. • Exactly 2 or 3 neighbors keep an existing cell alive. What's next? • Any other # of neighbors and the central cell dies… white cells are empty
Lab Problem: Creating life next_life_generation( A ) For each cell… • 3 live neighbors – life! • 2 live neighbors – same • 0, 1, 4, 5, 6, 7, or 8 live neighbors – death • computed all at once, not cell-by-cell: the ? at left does NOT come to life! ? http://www.math.com/students/wonders/life/life.html
Lab Problem: Creating life next_life_generation( A ) old generation is the input, A returns the next generation 0 0 1 2 3 4 5 1 2 3 4 5 0 0 1 1 2 2 3 3 4 4 5 5