EECS 110: Lec 7: Program Planning

Slides:



Advertisements
Similar presentations
HW 1: Problems 3 & 4 EC 1 & 2.
Advertisements

Complexity (Running Time)
Main task -write me a program
EECS 110: Lec 6: Fractals and Trutles Aleksandar Kuzmanovic Northwestern University
CS 5 Today CS 5 alien on strike! Claremont residents report droplets of water falling down-ward from the sky: unexplained meteorological phenomenon causes.
IS 313 Tomorrow… IS 313 last week ? 9/20/09 - today: beyond recursion! 9/27/09 - next wk: web technologies, pt 2 Assignment reminders... Which door to.
EECS 110: Lec 8: Lists of Lists Aleksandar Kuzmanovic Northwestern University
EECS 110: Lec 5: List Comprehensions Aleksandar Kuzmanovic Northwestern University
The building blocks of functional computing data, sequences conditionals recursion CS 121 today List Comprehensions map and applications.
EECS 110: Lec 6: Fractals and Trutles Aleksandar Kuzmanovic Northwestern University
CS 121 Today Fractals and Turtles! The Koch Curve how random…
Announcements Course evaluation Your opinion matters! Attendance grades Will be posted prior to the final Project 5 grades Will be posted prior to the.
EECS 110: Lec 3: Data Aleksandar Kuzmanovic Northwestern University
EECS 110: Lec 7: Program Planning Aleksandar Kuzmanovic Northwestern University
CS Class 04 Topics  Selection statement – IF  Expressions  More practice writing simple C++ programs Announcements  Read pages for next.
EECS 110: Lec 7: Program Planning Aleksandar Kuzmanovic Northwestern University
CS 121 Today Fractals and Turtles! The Koch Curve how random…
Greedy Algorithms Many of the slides are from Prof. Plaisted’s resources at University of North Carolina at Chapel Hill.
EECS 110: Lec 8: Lists of Lists
CMSC201 Computer Science I for Majors Lecture 19 – Recursion
List Algorithms Taken from notes by Dr. Neil Moore & Dr. Debby Keen
Week 2 - Wednesday CS 121.
CMSC201 Computer Science I for Majors Lecture 20 – Recursion (Continued) Prof. Katherine Gibson Based on slides from UPenn’s CIS 110, and from previous.
More on Functions (Part 2)
FLOWCHARTS Part 1.
EECS 110: Lec 9: Review for the Midterm Exam
EECS 110: Lec 5: List Comprehensions
EECS 110: Lec 5: List Comprehensions
Aleksandar Kuzmanovic Northwestern University
Greedy Method 6/22/2018 6:57 PM Presentation for use with the textbook, Algorithm Design and Applications, by M. T. Goodrich and R. Tamassia, Wiley, 2015.
Caesar Cipher: encipher
EECS 110: Lec 6: Fractals and Trutles
Introduction to Programmng in Python
Functions CIS 40 – Introduction to Programming in Python
EECS 110: Lec 4: Functions and Recursion
Engineering Innovation Center
Random numbers Taken from notes by Dr. Neil Moore
CMSC201 Computer Science I for Majors Lecture 16 – Recursion
Writing Functions( ) (Part 5)
ASU 101: The ASU Experience Computer Science Perspective
For -G7 programing language Teacher / Shamsa Hassan Alhassouni.
Intro to Computer Science CS1510 Dr. Sarah Diesburg
List Algorithms Taken from notes by Dr. Neil Moore
Merge Sort 11/28/2018 2:18 AM The Greedy Method The Greedy Method.
Merge Sort 11/28/2018 2:21 AM The Greedy Method The Greedy Method.
Merge Sort 11/28/2018 8:16 AM The Greedy Method The Greedy Method.
CMSC201 Computer Science I for Majors Lecture 19 – Recursion
Spring 2010 EECS 110: Homework I.
CMSC201 Computer Science I for Majors Lecture 17 – Recursion (cont)
Intro to Computer Science CS1510 Dr. Sarah Diesburg
EECS 110: Lec 4: Functions and Recursion
Programming We have seen various examples of programming languages
Merge Sort 1/17/2019 3:11 AM The Greedy Method The Greedy Method.
slides created by Marty Stepp and Alyssa Harding
Problem Solving Designing Algorithms.
More on Functions (Part 2)
Big problem  small steps
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg
Last Class We Covered Recursion Stacks Parts of a recursive function:
Programming with Data Lab 6
EECS 110: Lec 12: Mutable Data
EE 194/BIO 196: Modeling biological systems
Background for lab: the ord() function
Recursion Review Spring 2019 CS 1110
CMSC201 Computer Science I for Majors Lecture 12 – Program Design
Lecture 20 – Practice Exercises 4
Lecture 20 – Practice Exercises 4
Year 8 Computer Science Digital Portfolio
Lecture 6 - Recursion.
Presentation transcript:

EECS 110: Lec 7: Program Planning Aleksandar Kuzmanovic Northwestern University http://networks.cs.northwestern.edu/EECS110-s17/

Midterm and Final Midterm: Final: Wednesday 4/26/2017 9:30am – 11:30am Pancoe Life Science Pavilion (PLSAUD) Final: Wednesday 5/31/2017

EECS 110 Today Computing to the max Hw #3 due Sunday… The not-so-subtle art of singling out the best (and worst) of anything… Hw #3 due Sunday… Lights On! for fun and safety How to break apart a tough problem

(1) What does chai draw? def chai(size): """ mystery! """ forward(size) left(90) forward(size/2.0) right(90) backward(size) Why are there two identical commands in a row?

one possible result of rw(20) (2) Finish rwalk to draw a "stock-market-type" random path of nsteps steps. from random import * def rw(nsteps): """ moving for nsteps steps, randomly 45 deg. left/up or right/down """ if nsteps == 0: return if choice(['left','right']) == 'left': left(45) forward(20) right(45) else: # 'right‘ return rw(nsteps-1) one possible result of rw(20) What if we didn't go back to the starting pose?

Notes from prior hwks… Warnings! def rps(p1,p2): """ rock-paper-scissors judger """ if 'p1' == 'p2': return 0 def rps(p1,p2): if p1 == p2: return '0' def letterscore(let): if let in 'zq': return 10 …(lots more)…

Notes from prior hwks… Warnings! def rps(p1,p2): """ rock-paper-scissors judger """ if 'p1' == 'p2': return 0 The string 'p1' is not the same as the variable p1 ! def rps(p1,p2): """ rock-paper-scissors judger """ if p1 == p2: return '0' The string '0' is not the same as the number 0 ! no docstring! def letterscore(let): if let in 'zq': return 10 …(lots more)… Capital letters count! (It should be letterScore.)

thinking like a machine What CS is really about thinking like a machine variables 42 storage int guess sequences 'w' 'a' 'r' 't' str s[0] str s[1] str s[2] str s[3] if…elif…else making decisions “high” or “low” recursion repeated actions

thinking like a machine What CS is really about thinking like a machine thinking for a machine variables 42 library storage int guess deciding how to use these tools sequences 'w' 'a' 'r' 't' functions str s[0] str s[1] str s[2] str s[3] creating your own tools ... if…elif…else classes making decisions creating your own data structures ... “high” or “low” (later) recursion repeated actions

Top-down program design Given: a description of the problem translation! Wanted: a function that solves it

Top-down program design Given: a description of the problem translation! Wanted: a function that solves it with as much detail as possible 1. Visualize what the program will do 2. Break up the work into a set of smaller tasks 3. Compose solutions for these tasks (functions) variables, lists, if…elif…else, recursion What do you need for each? Are these tasks still too big? if so, go to step 1… 1. Visualize what the function will do ...

Top-down program design Given: a description of the problem translation! Wanted: a function that solves it with as much detail as possible 1. Visualize what the program will do 2. Break up the work into a set of smaller tasks How to do this… 3. Compose solutions for these tasks (functions) variables, lists, if…elif…else, recursion What do you need for each? Are these tasks still too big? if so, go to step 1… 1. Visualize what the function will do ...

Run it (randomly) 1000 times and see! Monte Carlo Monty Hall Suppose you always switch to the other door... What are the chances that you will win the car ? Run it (randomly) 1000 times and see! How can we write MCMH?

Monte Carlo Monty Hall How can we write MCMH? What is the input/output of your function? What data do we need to keep track of? (a) Input: N (int), number of iterations, initDoor (int), strategy: ‘switch’ Output: number of times you won. (b) Current N (current iteration) carDoor (where the car is actually in this iteration) - result (str), defines whether we lost or not.

Monte Carlo Monty Hall How can we write MCMH? What specific actions does your function need to take? -Given that our initial guess is 1, and that the strategy is ‘switch’, let me we should say whether we won or lost in this iteration.

Monte Carlo Monty Hall How can we write MCMH? Put it all together into an algorithm… N = 100 Init = 1 Method = ‘switch’ Recursion: If N == 0: Return 0 Else: carDoor = randchoice([1,2,3]) Given the carDoor, determine if you won or not (f1) N=N-1 Call the function again F1: If carDoor = 1 and method == ‘stay’: result = Car elif carDoor !=1 and method == ‘stay’: result = Spam Elif carDoor !=1 and method == ‘switch’: result = Car Else: result = Spam

Monte Carlo Monty Hall Then translate the algorithm to code! def MCMH( init, sors, N ): """ plays the same "Let's make a deal" game, N times returns the number of times you win the car """ if N == 0: return 0 # don't play, can't win carDoor = choice([1,2,3]) # where is the car? if init == carDoor and sors == 'stay': result = 'Car!' elif init == carDoor and sors == 'switch': result = 'Spam.' elif init != carDoor and sors == 'switch': result = 'Car!' else: result = 'Spam.' print( 'You get the', result ) if result == 'Car!': return 1 + MCMH( init, sors, N-1 ) else: return 0 + MCMH( init, sors, N-1 )

Sorting a List Sorting a List What is the input/output of the function? What data do we need to keep track of? [1,3,5,2,4] -> [5,4,3,2,1] We can keep track of the maximum or minimum element of the list

Sorting a List Sorting a List If we had an easy way to find the maximum of the list, how could we use this to sort the list? We can just use recursion: Base case: If the length of the list is empty, return an empty list Recursive step: Find the maximum element in the list, then remove the maximum element from the list and concatinate it with the recursive call to the rest of the list.

Taking only one… def removeOne( e, L ): """ this function removes one element e from the top level of the list L """ if len(L) == 0: return L # L is empty elif e == L[0]: return L[1:] # remove this one else: return L[0:1] + removeOne(e,L[1:]) # keep the non-e element and then keep going removeOne(42, [5,7,42,8,42]) removeOne('p', 'computer programming') [5,7,8,42] 'comuter programming'

max A recipe for life ? and python already has it for us… The hard part is knowing what we want to maximize!

to the max If we want the highest price… Google Inc to the max If we want the highest price… max( [449.5, 580.0, 562.4, 481.3, 498.3, 414.5] ) 'apr' 'may' 'jun' 'jul' 'aug' 'sep' What if the months are in there, as well? max([ [449.5,'apr'], [580.0,'may'], [562.4,'jun'], [481.3,'jul'], [498.3,'aug'], [414.5,'sep'] ])

"Best" word def scrabbleScore(w): # see homework #1! Let's abbreviate this function as scsc(w) def bestWord( L ): """ finds the "best" word from L, a list of words here, "best" means highest scrabble score """

"Best" word def scrabbleScore(w): # see homework #1! Let's abbreviate this function as scsc(w) def bestWord( L ): """ finds the "best" word from L, a list of words here, "best" means highest scrabble score """ if len(L) < 2: return elif else:

"Best" word def scrabbleScore(w): # see homework #1! Let's abbreviate this function as scsc(w) def bestWord( L ): """ finds the "best" word from L, a list of words here, "best" means highest scrabble score """ if len(L) < 2: return L[0] elif scsc(L[0]) < scsc(L[1]): return bestWord( L[1:] ) else: return bestWord( L[0:1] + L[2:] )

A suggestion def scrabbleScore(w): # see homework #1! Let's abbreviate this function as scsc(w) def bestWord( L ): """ returns the word in L w/max scrabble score """ LOL = [ [scsc(w), w] for w in L ] # LOL bestPair = max( LOL ) return bestPair[1]

The last word on bestWord def scrabbleScore(w): # see homework #1! Let's abbreviate this function as scsc(w) using raw recursion def bestWord( L ): """ finds the "best" word from L, a list of words here, "best" means highest scrabble score """ if len(L) < 2: return L[0] elif scsc(L[0]) < scsc(L[1]): return bestWord( L[1:] ) else: return bestWord( L[0:1] + L[2:] ) using max def bestWord( L ): """ returns the word in L w/max scrabble score """ LOL = [ [scsc(w), w] for w in L ] bestPair = max( LOL ) return bestPair[1]

What is bestNumber ? mode ? Examples >>> bestNumber( [ 10, 20, 30, 40, 50, 60, 70 ] ) 40 >>> bestNumber( [ 100, 200, 300, 400 ] ) 100 >>> bestNumber( [ 1, 2, 3, 4, 5, 6, 7, 8, 7 ] ) 8 >>> mode( [ 1, 2, 3, 4, 5, 6, 7, 8, 7 ] ) 7 What is bestNumber ? mode ?

"Quiz" Nothing but the best! Hints: Hint: Name(s): Hints: abs( x ) is built-in to Python Use bestWord as a guide: Write this function using max/min or recursively : def bestWord( L ): """ example code """ LOL = [ [scsc(w), w] for w in L ] bestPair = max( LOL ) return bestPair[1] def bestNumber( L ): """ returns the # in L closest to 42 """ Write this function however you like: Hint: Consider defining a helper function ! def mode( L ): """ returns the element appearing most often in L """

"Quiz" Solutions… def bestNumber( L ): abs( x ) is built-in to Python Solutions… Hints: Use bestWord as a guide: def bestWord( L ): """ example code """ LOL = [ [scsc(w), w] for w in L ] bestPair = max( LOL ) return bestPair[1] Write this function using max/min: def bestNumber( L ): """ returns the # in L closest to 42 ""“ LOL = [ [abs(w-42), w] for w in L ] bestPair = min( LOL ) return bestPair[1]

"Quiz" Solutions… def numberOfTimes( w, L ): Write this function however you like: Hint: Consider defining a helper function ! def numberOfTimes( w, L ): """ returns the # in times w repeats in L """ return sum([k==w for k in L]) def mode( L ): """ returns the element appearing most often in L """ LOL = [[numberOfTimes(w,L),w] for w in L] return max(LOL)[1]

Taking only one… def removeOne( e, L ): """ this function removes one element e from the top level of the list L """ if len(L) == 0: return L # L is empty elif e == L[0]: return L[1:] # remove this one else: return L[0:1] + removeOne(e,L[1:]) # keep the non-e element and then keep going removeOne(42, [5,7,42,8,42]) removeOne('p', 'computer programming') [5,7,8,42] 'comuter programming'

sort(L) def sort( L ): """ a list of elements in L, sorted from hi to low """ if len(L) < 1: return L else:

sort(L) def sort( L ): """ a list of elements in L, sorted from hi to low """ if len(L) < 1: return L else: return [max(L)] + sort(removeOne( max(L), L ))

sort(L, maxFun) def sort( L, maxFun ): """ a list of elements in L, sorted using maxFun """ if len(L) < 1: return L else: return

sort(L, maxFun) def sort( L, maxFun ): """ a list of elements in L, sorted using maxFun """ if len(L) < 1: return L else: return [maxFun(L)] + sort(removeOne( maxFun(L), L )) Will this work?

sort(L, maxFun) def sort( L, maxFun ): """ a list of elements in L, sorted using maxFun """ if len(L) < 1: return L else: return [maxFun(L)] + sort(removeOne( maxFun(L), L ), maxFun)

sort(L, maxFun) def sort( L, maxFun ): """ a list of elements in L, sorted using maxFun """ if len(L) < 1: return L else: return [maxFun(L)] + sort(removeOne( maxFun(L), L ), maxFun) What happens if you call >>>sort( L, min )

See you in Lab !