EECS 110: Lec 4: Functions and Recursion

Slides:



Advertisements
Similar presentations
This Week More Types boolean string Modules print statement Writing programs if statement Type boolean.
Advertisements

Today’s whether: if, elif, or else!
Structured programming
Python November 18, Unit 7. So Far We can get user input We can create variables We can convert values from one type to another using functions We can.
Line Continuation, Output Formatting, and Decision Structures CS303E: Elements of Computers and Programming.
PYTHON: PART 2 Catherine and Annie. VARIABLES  That last program was a little simple. You probably want something a little more challenging.  Let’s.
Now String theory To Do: Lists This stuff hurts my brane. when you learn string theory from google images… Goal: Thinking like a machine You should now.
EECS 110: Lec 17: Review for the Final Exam 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.
Fall, 2006Selection1 Choices, Choices, Choices! Selection in FORTRAN Nathan Friedman Fall, 2006.
The last CS lecture you’ll ever need! On Warner Brothers' insistence, we affirm that this 'C' does not stand for 'Chamber' and 'S' does not stand for 'Secrets.'
EECS 110: Lec 3: Data Aleksandar Kuzmanovic Northwestern University
Topics: IF If statements Else clauses. IF Statement For the conditional expression, evaluating to True or False, the simple IF statement is if : x = 7.
1 Example: Solution of Quadratic Equations We want to solve for real values of x, for given values of a, b, and c. The value of x can be determined from.
EECS 110: Lec 4: Functions and Recursion Aleksandar Kuzmanovic Northwestern University
IS 313 Tomorrow… IS 313 Today? 9/16/09 - today: recursion and beyond! 9/23/09 - next wk: no meeting (DC) 9/30/09 - following wk: for & while Homework functions.
The last CS lecture you’ll ever need! On Warner Brothers' insistence, we affirm that this 'C' does not stand for 'Chamber' and 'S' does not stand for 'Secrets.'
EECS 110: Lec 10: Definite Loops and User Input Aleksandar Kuzmanovic Northwestern University
EECS 110: Lec 3: Data Aleksandar Kuzmanovic Northwestern University
Xiaojuan Cai Computational Thinking 1 Lecture 7 Decision Structure Xiaojuan Cai (蔡小娟) Fall, 2015.
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
EECS 110: Lec 17: Review for the Final Exam Aleksandar Kuzmanovic Northwestern University
EECS 110: Lec 9: Review for the Midterm Exam Aleksandar Kuzmanovic Northwestern University
The last CS 5 lecture you’ll ever need! Inducing labor for the machine! == Reducing labor for humans! On Warner Brothers' insistence, we affirm that this.
EECS 110: Lec 3: Data Aleksandar Kuzmanovic Northwestern University
Primitive Data Types. int This is the type you are familiar with and have been using Stores an integer value (whole number) between -2,147,483,648 (-2.
CMSC201 Computer Science I for Majors Lecture 05 – Comparison Operators and Boolean (Logical) Operators Prof. Katherine Gibson Prof. Jeremy.
Python Basics.
CMSC201 Computer Science I for Majors Lecture 05 – Comparison Operators and Boolean (Logical) Operators Prof. Katherine Gibson Based on slides by Shawn.
Basic concepts of C++ Presented by Prof. Satyajit De
EECS 110: Lec 10: Definite Loops and User Input
EECS 110: Lec 17: Review for the Final Exam
EECS 110: Lec 9: Review for the Midterm Exam
A basic tutorial for fundamental concepts
Introduction to Python
EECS 110: Lec 5: List Comprehensions
Line Continuation, Output Formatting, and Decision Structures
EECS 110: Lec 5: List Comprehensions
Aleksandar Kuzmanovic Northwestern University
EGR 2261 Unit 4 Control Structures I: Selection
Variables, Expressions, and IO
CSC 108H: Introduction to Computer Programming
Functions CIS 40 – Introduction to Programming in Python
EECS 110: Lec 4: Functions and Recursion
The CS 5 Black Post Penguins Invade Dormitory
Testing UW CSE 160 Spring 2018.
As close as CS gets to magic
Another problem to solve…
Worksheet Key 9 11/14/2018 8:58 PM Quadratic Formula.
As close as CS gets to magic
Line Continuation, Output Formatting, and Decision Structures
Selection CIS 40 – Introduction to Programming in Python
EECS 110: Lec 10: Definite Loops and User Input
Testing UW CSE 160 Winter 2016.
Class 12.
Data types Numeric types Sequence types float int bool list str
Another problem to solve…
Spring 2010 EECS 110: Homework I.
CHAPTER FOUR VARIABLES AND CONSTANTS
Fundamentals of Functional Programming
Class 13 function example unstring if if else if elif else
COMPUTER PROGRAMMING SKILLS
Another problem to solve…
Recursion Review Spring 2019 CS 1110
Class code for pythonroom.com cchsp2cs
More Basics of Python Common types of data we will work with
Problem to solve Given four numbers, days, hours, minutes, and seconds, compute the total number of seconds that is equivalent to them. For example, 0.
message = 'You need parentheses for chemistry !'
Lecture 6 - Recursion.
Presentation transcript:

EECS 110: Lec 4: Functions and Recursion Aleksandar Kuzmanovic Northwestern University http://networks.cs.northwestern.edu/EECS110-s18/

message = 'You need parentheses for chemistry !' "Quiz" Raising and razing lists Name(s): pi = [3,1,4,1,5,9] Q = [ 'pi', "isn't", [4,2] ] message = 'You need parentheses for chemistry !' Part 1 Part 2 len(pi) Q[0] What are len(Q) Q[0:1] len(Q[1]) What are Q[0][1] Q[1][0] What slice of pi is [3,1,4] What slice of pi is [3,4,5] What is message[9:15] What are pi[0] * (pi[1] + pi[2]) and pi[0] * (pi[1:2] + pi[2:3]) What is message[::5] Extra! Mind Muddlers What is pi[pi[2]]? How many nested pi's before pi[…pi[0]…] produces an error?

message = 'You need parentheses for chemistry !' "Quiz" Raising and razing lists Name(s): pi = [3,1,4,1,5,9] Q = [ 'pi', "isn't", [4,2] ] message = 'You need parentheses for chemistry !' Part 1 Part 2 len(pi) Q[0] What are len(Q) Q[0:1] len(Q[1]) What are Q[0][1] Q[1][0] What slice of pi is [3,1,4] What slice of pi is [3,4,5] What is message[9:15] What are pi[0] * (pi[1] + pi[2]) and pi[0] * (pi[1:2] + pi[2:3]) What is message[::5] Extra! Mind Muddlers What is pi[pi[2]]? How many nested pi's before pi[…pi[0]…] produces an error?

>>> 3*'i' in 'alien' The in thing >>> 3*'i' in 'alien' False >>> 'i' in 'team' False >>> 'cs' in 'physics' True >>> ‘sleep' not in ‘EECS 110' True >>> 42 in [41,42,43] True a little bit different for lists… >>> 42 in [ [42], '42' ] False

Some basic, built-in functions: Functioning in Python Some basic, built-in functions: abs max min sum range round bool float int long list str absolute value of lists these change data from one type to another creates lists only as accurately as it can! The most important: help dir

Functioning in Python Far more are available in separate files, or modules: import math math.sqrt( 1764 ) dir(math) accesses math.py's functions lists all of math.py's functions same, but without typing math. all of the time… from math import * pi sin( pi/2 )

Functioning in Python # my own function! def dbl( x ): """ returns double its input, x """ return 2*x

Functioning in Python Some of Python's baggage… # my own function! def dbl( x ): """ returns double its input, x """ return 2*x keywords Some of Python's baggage… def starts the function return stops it immediately and sends back the return value Docstrings They become part of python's built-in help system! With each function be sure to include one that Comments describes overall what the function does, and explains what the inputs mean/are They begin with #

>>> undo('caf') >>> undo(undo('caf')) Functioning in Python def undo(s): """ this "undoes" its string input, s """ return 'de' + s >>> undo('caf') >>> undo(undo('caf'))

Conditional Statements ax**2 + bx + c = 0 If b**2 – 4*a*c is less than 0, then the equation has no solution If b**2 – 4*a*c is equal to 0, then the equation has 1 solution If b**2 – 4*a*c is greater than 0, then the equation has 2 solutions

Striving for simplicity… def qroots(a,b,c): """ qroots(a,b,c) returns a list of the real-number solutions to the quadratic equation ax**2 + bx + c = 0 input a: a number (int or float) input b: a number (int or float) input c: a number (int or float) """ if b**2 - 4*a*c < 0: return [ ] if b**2 - 4*a*c == 0: return [-b/(2*a)] else: return [(-b-(b**2 - 4*a*c)**0.5)/(2*a), (-b+(b**2 - 4*a*c)**0.5)/(2*a)] # If b**2 – 4*a*c is less than 0 # then the equation has no solution # If b**2 – 4*a*c is equal to 0 # then the equation has one solution # Otherwise, the equation has 2 solutions

Simpler to fix, if needed! Naming data == Saving time def qroots(a,b,c): """ qroots(a,b,c) returns a lost of the real-number solutions to the quadratic equation ax**2 + bx + c = 0 input a: a number (int or float) input b: a number (int or float) input c: a number (int or float) """ d = b**2 - 4*a*c if d < 0: return [ ] if d == 0: return [ -b/(2*a) ] r1 = (-b + d**0.5)/(2*a) r2 = (-b - d**0.5)/(2*a) if r1 > r2: return [ r2, r1 ] else: return [ r1, r2 ] Simpler to fix, if needed! Faster to run, as well…

Simpler to fix, if needed! Naming data == Saving time def qroots(a,b,c): """ qroots(a,b,c) returns a lost of the real-number solutions to the quadratic equation ax**2 + bx + c = 0 input a: a number (int or float) input b: a number (int or float) input c: a number (int or float) """ d = b**2 - 4*a*c if d < 0: return [ ] if d == 0: return [ -b/(2*a) ] r1 = (-b + d**0.5)/(2*a) r2 = (-b - d**0.5)/(2*a) if r1 > r2: return [ r2, r1 ] else: return [ r1, r2 ] Name once - use often! Simpler to fix, if needed! Faster to run, as well…

Functioning Python… Docstrings become part of python's help system # data gets named on the way IN to a function def qroots(a,b,c): """ qroots(a,b,c) returns a lost of roots to the quadratic equation ax**2 + bx + c = 0 input a: a number (int or float) input b: a number (int or float) input c: a number (int or float) """ d = b**2 - 4*a*c if d < 0: return [ ] if d == 0: return [ -b/(2*a) ] r1 = (-b + d**0.5)/(2*a) r2 = (-b - d**0.5)/(2*a) if r1 > r2: return [ r2, r1 ] else: return [ r1, r2 ] # notice that we don't get to name data on the way out… function defs must be at the very left Docstrings become part of python's help system Indenting indicates code "blocks" qroots "block" is 11 lines

How functions work… What is demo(-4) ? def demo(x): return x + f(x) def f(x): return 11*g(x) + g(x/2) def g(x): return -1 * x vault 713? What is demo(-4) ?

How functions work… What is demo(-4) ? def demo(x): demo return x + f(x) demo x = -4 return -4 + f(-4) def f(x): return 11*g(x) + g(x/2) def g(x): return -1 * x vault 713? What is demo(-4) ?

How functions work… What is demo(-4) ? def demo(x): demo return x + f(x) demo x = -4 return -4 + f(-4) def f(x): return 11*g(x) + g(x/2) f x = -4 def g(x): return -1 * x return 11*g(x) + g(x/2) vault 713? What is demo(-4) ?

How functions work… These are different x's ! What is demo(-4) ? def demo(x): return x + f(x) demo x = -4 return -4 + f(-4) def f(x): return 11*g(x) + g(x/2) f x = -4 def g(x): return -1 * x return 11*g(x) + g(x/2) These are different x's ! vault 713? What is demo(-4) ?

How functions work… What is demo(-4) ? def demo(x): demo return x + f(x) demo x = -4 return -4 + f(-4) def f(x): return 11*g(x) + g(x/2) f x = -4 def g(x): return -1 * x return 11*g(-4) + g(-4/2) g vault 713? x = -4 What is demo(-4) ? return -1.0 * x

How functions work… What is demo(-4) ? def demo(x): return x + f(x) return -4 + f(-4) def f(x): return 11*g(x) + g(x/2) f x = -4 def g(x): return -1 * x return 11* 4 + g(-4/2) g vault 713? x = -4 What is demo(-4) ? return -1 * -4 4

How functions work… What is demo(-4) ? def demo(x): demo return x + f(x) demo x = -4 return -4 + f(-4) def f(x): return 11*g(x) + g(x/2) f x = -4 def g(x): return -1.0 * x return 11* 4 + g(-4/2) vault 713? What is demo(-4) ?

How functions work… What is demo(-4) ? def demo(x): return x + f(x) return -4 + f(-4) def f(x): return 11*g(x) + g(x/2) f x = -4 def g(x): return -1 * x return 11* 4 + g(-4/2) g vault 713? x = -2 What is demo(-4) ? return -1 * -2 2

How functions work… What is demo(-4) ? def demo(x): demo return x + f(x) demo x = -4 return -4 + f(-4) def f(x): return 11*g(x) + g(x/2) f x = -4 def g(x): return -1.0 * x return 11* 4 + 2 vault 713? What is demo(-4) ?

How functions work… What is demo(-4) ? def demo(x): demo return x + f(x) demo x = -4 return -4 + f(-4) def f(x): return 11*g(x) + g(x/2) f x = -4 def g(x): return -1.0 * x return 11* 4 + 2 46 vault 713? What is demo(-4) ?

42 How functions work… What is demo(-4) ? def demo(x): demo return x + f(x) demo x = -4 return -4 + 46 def f(x): return 11*g(x) + g(x/2) def g(x): return -1.0 * x vault 713? What is demo(-4) ? 42

Thinking sequentially factorial 5! = 120 5! = 5 * 4 * 3 * 2 * 1 N! = N * (N-1) * (N-2) * … * 3 * 2 * 1

Recursion == self-reference! Thinking recursively Recursion == self-reference! factorial 5! = 120 5! = 5 * 4 * 3 * 2 * 1 N! = N * (N-1) * (N-2) * … * 3 * 2 * 1 N! = N * (N-1)!

Warning This is legal code! def fac(N): return N * fac(N-1)

Warning def fac(N): return N * fac(N-1) No base case -- the calls to factorial will never stop! Make sure you have a base case, then worry about the recursive step...

Thinking recursively ! def fac(N): if N <= 1: return 1 Base Case

Thinking recursively ! def fac(N): if N <= 1: return 1 else: return N * fac(N-1) Base Case Recursive Step Human: Base case and 1 step Computer: Everything else

The base case is No Problem! def fac(N): if N <= 1: return 1 else: return N * fac(N-1) Behind the curtain… fac(1) Result: 1 The base case is No Problem!

Behind the curtain… fac(5) def fac(N): if N <= 1: return 1 else: return N * fac(N-1) Behind the curtain… fac(5)

Behind the curtain… fac(5) 5 * fac(4) def fac(N): if N <= 1: return 1 else: return N * fac(N-1) Behind the curtain… fac(5) 5 * fac(4)

Behind the curtain… fac(5) 5 * fac(4) 4 * fac(3) def fac(N): if N <= 1: return 1 else: return N * fac(N-1) Behind the curtain… fac(5) 5 * fac(4) 4 * fac(3)

Behind the curtain… fac(5) 5 * fac(4) 4 * fac(3) 3 * fac(2) def fac(N): if N <= 1: return 1 else: return N * fac(N-1) Behind the curtain… fac(5) 5 * fac(4) 4 * fac(3) 3 * fac(2)

Behind the curtain… fac(5) 5 * fac(4) 4 * fac(3) 3 * fac(2) 2 * fac(1) def fac(N): if N <= 1: return 1 else: return N * fac(N-1) Behind the curtain… fac(5) 5 * fac(4) 4 * fac(3) 3 * fac(2) 2 * fac(1)

Behind the curtain… fac(5) 5 * fac(4) 4 * fac(3) 3 * fac(2) 2 * fac(1) def fac(N): if N <= 1: return 1 else: return N * fac(N-1) Behind the curtain… fac(5) "The Stack" 5 * fac(4) 4 * fac(3) 3 * fac(2) Remembers all of the individual calls to fac 2 * fac(1) 1

Behind the curtain… fac(5) 5 * fac(4) 4 * fac(3) 3 * fac(2) 2 * 1 def fac(N): if N <= 1: return 1 else: return N * fac(N-1) Behind the curtain… fac(5) 5 * fac(4) 4 * fac(3) 3 * fac(2) 2 * 1

Behind the curtain… fac(5) 5 * fac(4) 4 * fac(3) 3 * 2 def fac(N): if N <= 1: return 1 else: return N * fac(N-1) Behind the curtain… fac(5) 5 * fac(4) 4 * fac(3) 3 * 2

Behind the curtain… fac(5) 5 * fac(4) 4 * 6 def fac(N): if N <= 1: return 1 else: return N * fac(N-1) Behind the curtain… fac(5) 5 * fac(4) 4 * 6

Behind the curtain… fac(5) 5 * 24 def fac(N): if N <= 1: return 1 else: return N * fac(N-1) Behind the curtain… fac(5) 5 * 24

Let recursion do the work for you. Recursion Mantra Let recursion do the work for you.

Let recursion do the work for you. Recursion Mantra Let recursion do the work for you. Exploit self-similarity Less work ! Produce short, elegant code

Let recursion do the work for you. Recursion Mantra Let recursion do the work for you. Exploit self-similarity Less work ! Produce short, elegant code def fac(N): if N <= 1: return 1 else: return N * fac(N-1) You handle the base case – the easiest possible case to think of! Recursion does almost all of the rest of the problem!

You handle the base case – the easiest possible case to think of! One Step But you do need to do one small step… def fac(N): if N <= 1: return 1 else: return fac(N) You handle the base case – the easiest possible case to think of! This will not work

Breaking Up… s = "this has 2 t's" L = [ 21, 5, 16, 7 ] is easy to do with Python. s = "this has 2 t's" How do we get at the initial character of s? How do we get at ALL THE REST of s? L = [ 21, 5, 16, 7 ] How do we get at the initial element of L? How do we get at ALL the REST of L?

Breaking Up… s = "this has 2 t's" s[0] L = [ 21, 5, 16, 7 ] is easy to do with Python. s = "this has 2 t's" s[0] How do we get at the initial character of s? How do we get at ALL THE REST of s? L = [ 21, 5, 16, 7 ] How do we get at the initial element of L? How do we get at ALL the REST of L?

Breaking Up… s = "this has 2 t's" s[0] s[1:] L = [ 21, 5, 16, 7 ] is easy to do with Python. s = "this has 2 t's" s[0] How do we get at the initial character of s? How do we get at ALL THE REST of s? s[1:] L = [ 21, 5, 16, 7 ] How do we get at the initial element of L? How do we get at ALL the REST of L?

Breaking Up… s = "this has 2 t's" s[0] s[1:] L = [ 21, 5, 16, 7 ] L[0] is easy to do with Python. s = "this has 2 t's" s[0] How do we get at the initial character of s? How do we get at ALL THE REST of s? s[1:] L = [ 21, 5, 16, 7 ] L[0] How do we get at the initial element of L? How do we get at ALL the REST of L?

Breaking Up… s = "this has 2 t's" s[0] s[1:] L = [ 21, 5, 16, 7 ] L[0] is easy to do with Python. s = "this has 2 t's" s[0] How do we get at the initial character of s? How do we get at ALL THE REST of s? s[1:] L = [ 21, 5, 16, 7 ] L[0] How do we get at the initial element of L? How do we get at ALL the REST of L? L[1:]

Recursion Examples def mylen(s): """ input: any string, s output: the number of characters in s """

Recursion Examples def mylen(s): """ input: any string, s output: the number of characters in s """ if s == '': return else:

Recursion Examples def mylen(s): """ input: any string, s output: the number of characters in s """ if s == '': return 0 else: return 1 + mylen( s[1:] ) Will this work for lists?

Behind the curtain… mylen(‘eecs')

Behind the curtain… mylen(‘eecs') 1 + mylen('ecs')

Behind the curtain… mylen(‘eecs') 1 + mylen('ecs') 1 + mylen('cs')

Behind the curtain… mylen(‘eecs') 1 + mylen('ecs') 1 + mylen('cs') 1 + mylen('s')

Behind the curtain… mylen(‘eecs') 1 + mylen('ecs') 1 + mylen('cs') 1 + mylen('s') 1 + mylen('')

Behind the curtain… mylen(‘eecs') 1 + mylen('ecs') 1 + mylen('cs') 1 + mylen('s') 1 + mylen('') = 0

Recursion Examples def mymax(L): """ input: a NONEMPTY list, L output: L's maximum element """

Recursion Examples def mymax(L): """ input: a NONEMPTY list, L output: L's maximum element """ if len(L) == 1: return else:

Recursion Examples def mymax(L): """ input: a NONEMPTY list, L output: L's maximum element """ if len(L) == 1: return L[0] else: if L[0] < L[1]: return mymax( L[1:] ) return mymax( L[0:1] + L[2:] )

Behind the curtain… mymax( [1,7,3,42,5] )

sajak('wheel of fortune') == 6 "Quiz" on recursion Names: def power(b,p): def sajak(s): """ returns b to the p power using recursion, not ** inputs: ints b and p output: a float """ """ returns the number of vowels in the input string, s """ UOIAUAI power(5,2) == 25.0 sajak('wheel of fortune') == 6 Want more power? Handle negative values of p, as well. For example, power(5,-1) == 0.2 (or so)

def power(b,p): if p == 0: return if p > 0: else: # p < 0 """ inputs: base b and power p (an int) implements: b**p = b*b**(p-1) """ if p == 0: return if p > 0: else: # p < 0

def power(b,p): if p == 0: return 1 if p > 0: return else: """ inputs: base b and power p (an int) implements: b**p = b*b**(p-1) """ if p == 0: return 1 if p > 0: return else: # p < 0

def power(b,p): if p == 0: return 1 if p > 0: return b*power(b,p-1) """ inputs: base b and power p (an int) implements: b**p = b*b**(p-1) """ if p == 0: return 1 if p > 0: return b*power(b,p-1) else: # p < 0 return

def power(b,p): if p == 0: return 1 if p > 0: return b*power(b,p-1) """ inputs: base b and power p (an int) implements: b**p = b*b**(p-1) """ if p == 0: return 1 if p > 0: return b*power(b,p-1) else: # p < 0 return 1/power(b,-1*p)

behind the curtain power(2,3)

def sajak(s): Base case? Rec. step? when there are no letters, there are ZERO vowels Base case? Look at the initial character. if it is NOT a vowel, the answer is Rec. step? if it IS a vowel, the answer is

def sajak(s): Base case? Rec. step? when there are no letters, there are ZERO vowels Base case? Look at the initial character. if it is NOT a vowel, the answer is just the number of vowels in the rest of s Rec. step? if it IS a vowel, the answer is 1 + the number of vowels in the rest of s

Checking for a vowel: Try #1 def sajak(s): if len(s) == 0: return 0 else: Base Case Checking for a vowel: Try #1

Checking for a vowel: Try #1 def sajak(s): if len(s) == 0: return 0 else: Base Case Checking for a vowel: Try #1 and or same as in English! but each side has to be a complete boolean value! not

Checking for a vowel: Try #1 def sajak(s): if len(s) == 0: return 0 else: Base Case if s[0] == 'a' or s[0] == 'e' or… Checking for a vowel: Try #1 and or same as in English! but each side has to be a complete boolean value! not

Checking for a vowel: Try #2 def sajak(s): if len(s) == 0: return 0 else: Base Case in Checking for a vowel: Try #2

def sajak(s): if len(s) == 0: return 0 else: if s[0] not in 'aeiou': return sajak(s[1:]) return 1+sajak(s[1:]) Base Case Rec. Step if it is NOT a vowel, the answer is just the number of vowels in the rest of s if it IS a vowel, the answer is 1 + the number of vowels in the rest of s

behind the curtain sajak('eerier')

Good luck with Homework #1 The key to understanding recursion is to first understand recursion… - advice from a student