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

Post on 29-Mar-2015

220 Views

Category:

Documents

3 Downloads

Preview:

Click to see full reader

Transcript

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…

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…

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!

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!

Fix #1: convert to the right type

meters_str = raw_input('How many m? ') meters = float( meters_str )cm = meters * 100print 'That is', cm, 'cm.'

name: meters type: float

name: cmtype: float

42.0 4200.0

name: meters_str type: string

'42'

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

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) QuitEnter your choice:

hw6pr1: T. T. Securities (TTS)

L = [ 40, 80, 10, 30, 27, 52, 5, 15 ]

day0

day1

day2

day3

day4

day5

day6

day7

Analyzes a sequence of stock prices

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) QuitEnter your choice:

hw6pr1: T. T. Securities (TTS)

L = [ 40, 80, 10, 30, 27, 52, 5, 15 ]

day0

day1

day2

day3

day4

day5

day6

day7

Analyzes a sequence of stock prices

Loop Review!

A larger applicationdef 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

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…

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…

Functions you'll writeAll 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) QuitEnter your choice:

def stdev( L )

def minday( L )

def maxday( L )

(L[i] - Lav)2

len(L)i

webbrowser.open_new_tab(url)

Min price

L = [ 40, 80, 10, 30, 27, 52, 5, 15 ]

day0

day1

day2

day3

day4

day5

day6

day7

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 ?

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 ]

day0

day1

day2

day3

day4

day5

day6

day7

What about the day of the

minimum price?

m = 40

m = 10

m = 5

5 is returned

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] )

20 1 2 3 4

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?

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] )

20 1 2 3 4

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!

personal motivation for TT securities…

LightPath, Summer 1999 ~ wedding gift…

LightPath, Summer 1999

LightPath, Spring 2000

LightPath, Fall 2013

Why it's called a brokerage

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) QuitEnter your choice:

T. T. Securities

Hardware side…

Investment analysis for the 21st century … and beyond!

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) QuitEnter your choice:

T. T. Securities

Hardware side…

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) QuitEnter your choice:

T. T. Securities

Hardware side…

Back to the future

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 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 after you buy.

In CS, rules rule!

(1a) Numbers and strings are handled "by value"(1b) Lists are handled "by reference"

LL[0] L[1] L[2]

Reference

Pointer

id L = [5,42,'hi']

5 42 'hi'

s

'hi'

s = 'hi'

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.

7fav

7fav

f( fav )copy of fav

LL[0] L[1] L[2]

Reference

Pointer

id L = [5,42,'hi']

5 42 'hi'

s

'hi'

s = 'hi'

Reference vs. Value

LL[0] L[1] L[2]

Reference

Pointer

id

L = [5,42,'hi']

5 42 'hi' s

'hi'

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

Python functions: pass by value

def main()

print " Welcome! "

fav = 7 conform(fav)

print " My favorite # is", fav

7

fav

fav

def conform(fav)

fav = 42 return fav

But what if the underlined part were absent… ?

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

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

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

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

Differing approaches to rules …

Mathematicians

CS?

Engineers

Physicistsdifferent worldviews…

Engineers believe equations approximate reality;

"the rules"

Grand Canyon Skywalk

Safety margins!

Engineers believe equations approximate reality;

Physicists believe reality approximates equations…

Not a parabola, so not a real shot!

http://www.youtube.com/watch?feature=player_embedded&v=WbaH52JI3Sohttp://www.fourandsix.com/blog/2011/8/29/seriously-amazing-beer-pong-shots.html

Image forensics' verdict:Fake!

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"

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?

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

variableslists

CS worldview

Insights, tools, algorithms

proofs programs

2D data!

One rule rules them all:

everything's a list!

Lists ~ 2D data

A = [ 42, 75, 70 ]

42 75 70int int intlist

A

1D lists are familiar – but lists can hold ANY kind of data – including lists!

One rule rules them all:

everything's a list!

listA

Lists ~ 2D data

list

list

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 42.

1 2 4

?

3

5 6

7 8 109 11

Where's 3?

listA

list

list

list

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] ]

1 2 3 4

5 6 7 8

9 0 1 2

To try…

Rectangular 2D data

Try it…

1 2 3 4

5 6 7 8

9 10 11 12

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 1 col 2 col 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?

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

hw6pr2: John Conway's Game of Life

Evolutionary rulesGrid 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

white cells are empty

Lab Problem: Conway's Game of Life

Evolutionary rulesGrid 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…

white cells are empty

Lab Problem: Conway's Game of Life

Evolutionary rulesGrid 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…

red cells are alive

white cells are empty

Lab Problem: Conway's Game of Life

Evolutionary rulesGrid 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?

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 )

0 1 2 3 4 50 1 2 3 4 5

0

1

2

3

4

5

0

1

2

3

4

5

next_life_generation( A )

old generation is the input, A returns the next generation

Lab Problem: Creating life

Stable configurations:

Periodic

"rocks"

"plants"

"animals"

period 3period 2

Lab Problem: Creating life

Self-propagatingglider

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?

www.ibiblio.org/lifepatterns/

"glider"

"Gosper glider gun"

Lab Problem: Creating life

Wait! What are complex numbers…?

extra! the Mandelbrot Set

Consider an update rule for all complex numbers c

z0 = 0

zn+1 = zn2 + c

c

z0

z1z2

z3

z4

Real axis

Imaginary axis

Complex numbers…

Consider an update rule for all complex numbers c

z0 = 0

zn+1 = zn2 + c

Small values of c keep the sequence near the

origin, 0+0j.

z0

z1z2

z3

z4

Real axis

Imaginary axis

Complex numbers…

Complex numbers are simply ordinary 2d points

z3 is 4 + 2i

x ~ "real" part y ~ "imaginary" part z = x + yi ~ complex #

z1 is ~

zlost is ~zlost

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 – 2010c

Small values of c keep the sequence near the

origin, 0+0j.

c

Consider an update rule for all complex numbers c

z0 = 0

zn+1 = zn2 + c

Nothing's too complex for

Python!

Python's complex #s

>>> c = 3 + 4j

>>> c.real3.0

>>> c.imag4.0

>>> abs(c)5.0

Mandelbrot Set ~ low-res version

The shaded area are points that do not diverge for z = z**2 + c

Higher-resolution M. Set

The black pixels are points that do not diverge for z = z**2 + c

-2 + 1j

-2 - 1j

1 + 1j

1 - 1j

connected

finite area

perimeter!

Chaos!

http://www.youtube.com/watch?v=0jGaio87u3A

not 100% self-similar but quasi-self-similar

Zooming in reveals more and more detail, not less:

What are these colors?

The black pixels are points that do not diverge for z = z**2 + c

What are these colors?

The black pixels are points that do not diverge for z = z**2 + c

escape velocities

Happy Mandelbrotting!

www.cs.hmc.edu/~jgrasel/projects

Good luck with

Hwks #5 and 6!

We meet again on

March 31!

top related