Presentation is loading. Please wait.

Presentation is loading. Please wait.

IST380 Loops got you going in circles? Nest them! nested loops == 2d data infinitely nested structure… from finitely nested loops Schedule 3/10 2day ==

Similar presentations


Presentation on theme: "IST380 Loops got you going in circles? Nest them! nested loops == 2d data infinitely nested structure… from finitely nested loops Schedule 3/10 2day =="— Presentation transcript:

1 IST380 Loops got you going in circles? Nest them! nested loops == 2d data infinitely nested structure… from finitely nested loops Schedule 3/10 2day == 2d data 3/17 spring break! 3/24 no class 3/31 we meet again…

2 User input What will Python think? meters = raw_input('How many m? ') cm = meters * 100 print 'That is', cm, 'cm.' I think I like these units better than light years per year! You know you've become a programmer when you ask yourself…

3 User input What will Python think? meters = raw_input('How many m? ') cm = meters * 100 print 'That is', cm, 'cm.' I think I like these units better than light years per year!

4 User input What will Python think? meters = raw_input('How many m? ') cm = meters * 100 print 'That is', cm, 'cm.' I think I like these units better than light years per year! raw_input ALWAYS returns a string – no matter what has been typed!

5 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.' name: meters type: float name: cm type: float name: meters_str type: string '42'

6 meters = input('How many m? ') cm = meters * 100 print 'That is', cm, 'cm.' I always use input -- but don't "quote" me on that. Fix #2: use input input interprets its input raw_input always returns a string

7 The menu to implement: (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: hw6pr1: T. T. Securities (TTS) L = [ 40, 80, 10, 30, 27, 52, 5, 15 ] day 0 day 1 day 2 day 3 day 4 day 5 day 6 day 7 Analyzes a sequence of stock prices

8 The menu to implement: (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: hw6pr1: T. T. Securities (TTS) L = [ 40, 80, 10, 30, 27, 52, 5, 15 ] day 0 day 1 day 2 day 3 day 4 day 5 day 6 day 7 Analyzes a sequence of stock prices Loop Review!

9 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 """ while True: menu() uc = input('Which option? ') Perhaps uc the reason for this? Calls a helper function

10 def main(): """ handles user input for our menu """ L = [2,12,22,32] # a starting list while True: menu() # print menu uc = input('Which option? ') if uc == 9: elif uc == 1: elif uc == 2: (9) Quit! (1) Get new list (2) other…

11 def main(): """ handles user input for our menu """ L = [2,12,22,32] # a starting list while True: menu() # print menu uc = input('Which option? ') if uc == 9: elif uc == 1: elif uc == 2: break exits the loop use input to get a new L other functions, as needed (9) Quit! (1) Get new list (2) other…

12 Functions you'll write All use loops… def average( L ) Menu (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: def stdev( L ) def minday( L ) def maxday( L ) (L[i] - L av ) 2 len(L) i webbrowser.open_new_tab(url)

13 Min price L = [ 40, 80, 10, 30, 27, 52, 5, 15 ] day 0 day 1 day 2 day 3 day 4 day 5 day 6 day 7 What's the idea for finding the smallest (minimum) price? m = track the value of the minimum so far as you loop over L m is the "min so far" Just call min ?

14 Min price vs. min day def minprice( L ): m = L[0] for x in L: if x < m: m = x return m L = [ 40, 80, 10, 30, 27, 52, 5, 15 ] day 0 day 1 day 2 day 3 day 4 day 5 day 6 day 7 What about the day of the minimum price? m = 40 m = 10 m = 5 5 is returned

15 def minday( L ): m = L[0] mndy = 0 for : if < m: m = return mndy index-based loop minday return the index of L's minimum. >>> minday( [9, 8, 5, 7, 42] ) L index 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 ?

16 def minday( L ): m = L[0] mndy = 0 day = 0 for x in L: if x < m: m = x mndy = day day += 1 return mndy element-based loop minday return the index of L's minimum. >>> minday( [9, 8, 5, 7, 42] ) L index 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!

17 personal motivation for TT securities… LightPath, Summer 1999 ~ wedding gift…

18 LightPath, Summer 1999

19 LightPath, Spring 2000

20 LightPath, Fall 2013 Why it's called a brokerage

21 Software side … (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: T. T. Securities Hardware side… Investment analysis for the 21st century … and beyond!

22 Software side … (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: T. T. Securities Hardware side…

23 Investment analysis for the 21st century … and beyond! Software side … (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: T. T. Securities Hardware side… Back to the future

24 The TTS advantage! Your stock's prices: What is the best TTS investment strategy here? L = [ 40, 80, 10, 30, 27, 52, 5, 15 ] Day Price To be realistic, however (for our VC backers and the SEC), you may only sell after you buy.

25 In CS, rules rule! (1a) Numbers and strings are handled "by value" (1b) Lists are handled "by reference" L L[0]L[1]L[2] Reference Pointer id L = [5,42,'hi'] 5 42 'hi' s s = 'hi'

26 In CS, rules rule! (1a) Numbers and strings are handled "by value" (1b) Lists are handled "by reference" (2) Inputs pass to functions "by value" The contents of the variable's "box" in memory are copied. 7 fav 7 f( fav ) copy of fav L L[0]L[1]L[2] Reference Pointer id L = [5,42,'hi'] 5 42 'hi' s s = 'hi'

27 Reference vs. Value L L[0]L[1]L[2] Reference Pointer id L = [5,42,'hi'] 5 42 'hi' s s = 'hi' Whee! Python's two methods for handling data 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

28 Python functions: pass by value def main() print " Welcome! " fav = 7 conform(fav) print " My favorite # is", fav 7 fav def conform(fav) fav = 42 return fav But what if the underlined part were absent… ?

29 Python functions: pass by value def main() print " Welcome! " fav = 7 conform(fav) print " My favorite # is", fav 7 fav def conform(fav) fav = 42 return fav 7 copy of fav "pass by value" means the contents of fav are copied to fav fav But what if the underlined part were absent… ? 42

30 Python functions: pass by value def main() print " Welcome! " fav = [7,11] conform(fav) print " My favorite #s: ", fav 7 fav[0] fav def conform(fav) fav[0] = 42 fav[1] = 42 return fav But what if the underlined part were absent… ? 11 fav[1] fav

31 Python functions: pass by value def main() print " Welcome! " fav = [7,11] conform(fav) print " My favorite #s: ", fav 7 fav[0] fav def conform(fav) fav[0] = 42 fav[1] = 42 return fav But what if the underlined part were absent… ? 11 fav[1] fav

32 Lists are Mutable You can change the contents of lists in functions that take those lists as input. Those changes will be visible everywhere. - Lists are MUTABLE objects Numbers, strings, etc. are IMMUTABLE – they can't be changed, only reassigned. One rule rules them all: pass-by-value

33 Differing approaches to rules … Mathematicians CS? Engineers Physicists different worldviews…

34 Engineers believe equations approximate reality; "the rules" Grand Canyon Skywalk Safety margins!

35 Engineers believe equations approximate reality; Physicists believe reality approximates equations… Not a parabola, so not a real shot! Image forensics' verdict: Fake!

36 Mathematicians don't care either way! Engineers believe equations approximate reality; Physicists believe reality approximates equations… 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"

37 Mathematicians don't care either way! Don't like reality? Build a new one! Engineers believe equations approximate reality; Physicists believe reality approximates equations… In CS? why settle for gears, when you could have fractal gears?

38 Axioms Definitions math worldview Mathematics reasons about structural rules… Engineers believe equations approximate reality; Physicists believe reality approximates equations… … and CS reasons about procedural ones. Insights, tools, truths if/else while for arithmetic operations variables lists CS worldview Insights, tools, algorithms proofs programs

39 2D data! One rule rules them all: everything's a list!

40 Lists ~ 2D data A = [ 42, 75, 70 ] int list A 1D lists are familiar – but lists can hold ANY kind of data – including lists! One rule rules them all: everything's a list!

41 list A Lists ~ 2D data list A[0] A[1] A[2] A = [ [1,2,3,4], [5,6], [7,8,9,10,11] ] A[0][0] A[0][1] A[0][3] A[1][0] A[1][1] A[2][0]A[2][1]A[2][2]A[2][3]A[2][4] len(A[0])len(A) Replace 10 with ? Where's 3?

42 list A A[0] A[1] A[2] How many rows does A have, in general ? How many columns does A have, in general ? What does each component of A[1][2] mean ? What is A[1][2]? A[2][3] A[0][0] A = [ [1,2,3,4], [5,6,7,8], [9,0,1,2] ] To try… Rectangular 2D data

43 Try it… 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 Before After A A row 0 row 1 row 2 col 0 col 1col 2col 3 What are the resulting values in A? 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?

44 hw6pr2: John Conway's Game of Life red cells are "alive" white cells are empty Are there a few simple rules that could give rise to intricate, complex phenomena… They need to be local Chemistry ~ life! How? John Conway

45 hw6pr2: John Conway's Game of Life Evolutionary rules Grid World Everything depends on a cell's eight neighbors red cells are "alive" white cells are empty 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… Only 3 rules

46 white cells are empty Lab Problem: Conway's Game of Life Evolutionary rules Grid World Everything depends on a cell's eight neighbors red cells are "alive" 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…

47 white cells are empty Lab Problem: Conway's Game of Life Evolutionary rules Grid World Everything depends on a cell's eight neighbors red cells are "alive" 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…

48 red cells are alive white cells are empty Lab Problem: Conway's Game of Life Evolutionary rules Grid World 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… What's next?

49 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! ? Lab Problem: Creating life next_life_generation( A )

50 old generation is the input, Areturns the next generation Lab Problem: Creating life

51 Stable configurations: Periodic "rocks" "plants" "animals" period 3 period 2 Lab Problem: Creating life Self-propagating glider

52 Many life configurations expand forever… What is the largest amount of the life universe that can be filled with cells? How sophisticated can Life-structures get? "glider" "Gosper glider gun" Lab Problem: Creating life

53 Wait! What are complex numbers…? extra! the Mandelbrot Set Consider an update rule for all complex numbers c z 0 = 0 z n+1 = z n 2 + c

54 c z0z0 z1z1 z2z2 z3z3 z4z4 Real axis Imaginary axis Complex numbers… Consider an update rule for all complex numbers c z 0 = 0 z n+1 = z n 2 + c Small values of c keep the sequence near the origin, 0+0j.

55 z0z0 z1z1 z2z2 z3z3 z4z4 Real axis Imaginary axis Complex numbers… Complex numbers are simply ordinary 2d points z 3 is 4 + 2i x ~ "real" part y ~ "imaginary" part z = x + yi ~ complex # z 1 is ~ z lost is ~ z lost

56 Which c's stick around? Mandelbrot Definition Real axis Imaginary axis Large values of c make the sequence head to infinity. Benoit B. Mandelbrot 1924 – 2010 c Small values of c keep the sequence near the origin, 0+0j. c Consider an update rule for all complex numbers c z 0 = 0 z n+1 = z n 2 + c

57 Nothing's too complex for Python! Python's complex #s >>> c = 3 + 4j >>> c.real 3.0 >>> c.imag 4.0 >>> abs(c) 5.0

58 Mandelbrot Set ~ low-res version The shaded area are points that do not diverge for z = z**2 + c

59 Higher-resolution M. Set The black pixels are points that do not diverge for z = z**2 + c j j 1 + 1j 1 - 1j connected finite area perimeter!

60 Chaos! not 100% self-similar but quasi-self-similar Zooming in reveals more and more detail, not less:

61 What are these colors? The black pixels are points that do not diverge for z = z**2 + c

62 What are these colors? The black pixels are points that do not diverge for z = z**2 + c escape velocities

63 Happy Mandelbrotting!

64 Good luck with Hwks #5 and 6! We meet again on March 31!


Download ppt "IST380 Loops got you going in circles? Nest them! nested loops == 2d data infinitely nested structure… from finitely nested loops Schedule 3/10 2day =="

Similar presentations


Ads by Google