MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES...
Transcript of MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES...
![Page 1: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/1.jpg)
RECURSION, DICTIONARIES (download slides and .py files and follow along!)
6.0001 LECTURE 6
6.0001LECTURE6 1
![Page 2: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/2.jpg)
QUIZ PREP § apaperandanonlinecomponent
§ openbook/notes
§ notopenInternet,notopencomputer
§startprinSngoutwhateveryoumaywanttobring
6.0001LECTURE6 2
![Page 3: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/3.jpg)
LAST TIME §tuples-immutable
§lists-mutable
§aliasing,cloning
§mutabilitysideeffects
6.0001LECTURE6 3
![Page 4: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/4.jpg)
TODAY § recursion–divide/decreaseandconquer
§dicSonaries–anothermutableobjecttype
6.0001LECTURE6 4
![Page 5: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/5.jpg)
RECURSION RecursionistheprocessofrepeaSngitemsinaself-similarway.
6.0001LECTURE6 5
![Page 6: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/6.jpg)
WHAT IS RECURSION? §Algorithmically:awaytodesignsoluSonstoproblemsbydivide-and-conquerordecrease-and-conquer◦ reduceaproblemtosimplerversionsofthesameproblem
§SemanScally:aprogrammingtechniquewhereafunc0oncallsitself◦ inprogramming,goalistoNOThaveinfiniterecursion◦ musthave1ormorebasecasesthatareeasytosolve◦ mustsolvethesameproblemonsomeotherinputwiththegoalofsimplifyingthelargerprobleminput
6.0001LECTURE6 6
![Page 7: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/7.jpg)
ITERATIVE ALGORITHMS SO FAR §loopingconstructs(whileandforloops)leadtoitera0vealgorithms
§cancapturecomputaSoninasetofstatevariablesthatupdateoneachiteraSonthroughloop
6.0001LECTURE6 7
![Page 8: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/8.jpg)
MULTIPLICATION – ITERATIVE SOLUTION §“mulSplya*b”isequivalentto“addatoitselfbSmes”
a + a + a + a + … + a §capturestateby◦ anitera0onnumber(i)startsatb i ß i-1andstopwhen0 0a 1a 2a 3a 4a
lt)◦ acurrentvalueofcomputa0on(resu result ß result + a
def mult_iter(a, b): result = 0
while b > 0: += aresult
b -= 1 return result
6.0001LECTURE6 8
![Page 9: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/9.jpg)
a*b = a + a + a + a + … + a
= a + a + a + a + … + a
= a + a * (b-1)
MULTIPLICATION – RECURSIVE SOLUTION §recursivestep
• thinkhowtoreduceproblemtoasimpler/smallerversionofsameproblem
§basecase• keepreducingproblemunSlreachasimplecasethatcanbesolveddirectly
• whenb=1,a*b=a
6.0001LECTURE6 9
def mult(a, b):
if b == 1:
return a
else:
return a + mult(a, b-1)
![Page 10: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/10.jpg)
FACTORIAL n! = n*(n-1)*(n-2)*(n-3)* … * 1
§forwhatndoweknowthefactorial?n=1 à if n == 1:
return 1
§howtoreduceproblem?Rewriteintermsofsomethingsimplertoreachbasecasen*(n-1)! à else:
return n*factorial(n-1)
6.0001LECTURE6 10
![Page 11: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/11.jpg)
RECURSIVE FUNCTION SCOPE EXAMPLE
6.0001LECTURE6 11
Globalscope
fact Somecode
factscope(callw/n=4)
n4
factscope(callw/n=3)
n3
factscope(callw/n=2)
n2
factscope(callw/n=1)
n1
def fact(n): if n == 1:
return 1 else:
return n*fact(n-1)
print(fact(4))
![Page 12: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/12.jpg)
SOME OBSERVATIONS
§eachrecursivecalltoafuncSoncreatesitsownscope/environment
§bindingsofvariablesinascopearenotchangedbyrecursivecall
§flowofcontrolpassesbacktopreviousscopeoncefuncSoncallreturnsvalue
6.0001LECTURE6 12
![Page 13: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/13.jpg)
ITERATION vs. RECURSION def factorial_iter(n): def factorial(n):
prod = 1 if n == 1:
for i in range(1,n+1): return 1
prod *= i else:
return prod return n*factorial(n-1)
6.0001LECTURE6 13
§ recursionmaybesimpler,moreintuiSve§ recursionmaybeefficientfromprogrammerPOV§ recursionmaynotbeefficientfromcomputerPOV
![Page 14: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/14.jpg)
INDUCTIVE REASONING §Howdoweknowthatour def mult_iter(a, b):recursivecodewillwork? result = 0
§mult_iterterminates while b > 0:becausebisiniSallyposiSve, result += aanddecreasesby1eachSmearoundloop;thusmust b -= 1
eventuallybecomelessthan1 return result
§multcalledwithb=1hasnorecursivecallandstops def mult(a, b):
§multcalledwithb>1makes if b == 1:arecursivecallwithasmaller return aversionofb;musteventuallyreachcallwithb=1 else:
return a + mult(a, b-1)
6.0001LECTURE6 14
![Page 15: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/15.jpg)
MATHEMATICAL INDUCTION §Toproveastatementindexedonintegersistrueforallvaluesofn:◦ Proveitistruewhennissmallestvalue(e.g.n=0orn=1)◦ Thenprovethatifitistrueforanarbitraryvalueofn,onecanshowthatitmustbetrueforn+1
6.0001LECTURE6 15
![Page 16: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/16.jpg)
EXAMPLE OF INDUCTION §0+1+2+3+…+n=(n(n+1))/2
§Proof:◦ Ifn=0,thenLHSis0andRHSis0*1/2=0,sotrue◦ Assumetrueforsomek,thenneedtoshowthat0+1+2+…+k+(k+1)=((k+1)(k+2))/2◦ LHSisk(k+1)/2+(k+1)byassumpSonthatpropertyholdsforproblemofsizek
◦ Thisbecomes,byalgebra,((k+1)(k+2))/2◦ Henceexpressionholdsforalln>=0
6.0001LECTURE6 16
![Page 17: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/17.jpg)
RELEVANCE TO CODE? §Samelogicapplies
def mult(a, b):
if b == 1:
return a
else:
return a + mult(a, b-1)
§Basecase,wecanshowthatmult mustreturncorrectanswer
§Forrecursivecase,wecanassumethatmult correctlyreturnsananswerforproblemsofsizesmallerthanb,thenbytheaddiSonstep,itmustalsoreturnacorrectanswerforproblemofsizeb
§ThusbyinducSon,codecorrectlyreturnsanswer
6.0001LECTURE6 17
![Page 18: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/18.jpg)
TOWERS OF HANOI § Thestory:◦ 3tallspikes◦ Stackof64differentsizeddiscs–startononespike◦ Needtomovestacktosecondspike(atwhichpointuniverseends)
◦ CanonlymoveonediscataSme,andalargerdisccannevercoverupasmalldisc
6.0001LECTURE6 18
![Page 19: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/19.jpg)
TOWERS OF HANOI §Havingseenasetofexamplesofdifferentsizedstacks,howwouldyouwriteaprogramtoprintouttherightsetofmoves?
§Thinkrecursively!◦ Solveasmallerproblem◦ Solveabasicproblem◦ Solveasmallerproblem
6.0001LECTURE6 19
![Page 20: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/20.jpg)
6.0001LECTURE6 20
def printMove(fr, to):
print('move from ' + str(fr) + ' to ' + str(to))
def Towers(n, fr, to, spare):
if n == 1:
printMove(fr, to)
else:
Towers(n-1, fr, spare, to)
Towers(1, fr, to, spare)
Towers(n-1, spare, to, fr)
![Page 21: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/21.jpg)
RECURSION WITH MULTIPLE BASE CASES §Fibonaccinumbers◦ LeonardoofPisa(akaFibonacci)modeledthefollowingchallenge◦ Newbornpairofrabbits(onefemale,onemale)areputinapen◦ Rabbitsmateatageofonemonth◦ RabbitshaveaonemonthgestaSonperiod◦ Assumerabbitsneverdie,thatfemalealwaysproducesonenewpair(onemale,onefemale)everymonthfromitssecondmonthon.
◦ Howmanyfemalerabbitsarethereattheendofoneyear?
6.0001LECTURE6 21
![Page 22: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/22.jpg)
DemocourtesyofProf.DennyFreemanandAdamHartz
6.0001LECTURE6 22
![Page 23: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/23.jpg)
DemocourtesyofProf.DennyFreemanandAdamHartz
6.0001LECTURE6 23
![Page 24: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/24.jpg)
DemocourtesyofProf.DennyFreemanandAdamHartz
6.0001LECTURE6 24
![Page 25: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/25.jpg)
DemocourtesyofProf.DennyFreemanandAdamHartz
6.0001LECTURE6 25
![Page 26: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/26.jpg)
DemocourtesyofProf.DennyFreemanandAdamHartz
6.0001LECTURE6 26
![Page 27: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/27.jpg)
DemocourtesyofProf.DennyFreemanandAdamHartz
6.0001LECTURE6 27
![Page 28: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/28.jpg)
DemocourtesyofProf.DennyFreemanandAdamHartz
6.0001LECTURE6 28
![Page 29: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/29.jpg)
6.0001LECTURE6 29
![Page 30: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/30.jpg)
DemocourtesyofProf.DennyFreemanandAdamHartz
6.0001LECTURE6 30
![Page 31: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/31.jpg)
DemocourtesyofProf.DennyFreemanandAdamHartz
6.0001LECTURE6 31
![Page 32: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/32.jpg)
FIBONACCI Ayeronemonth(callit0)–1female
Ayersecondmonth–sSll1female(nowpregnant)
Ayerthirdmonth–twofemales,onepregnant,onenot
Ingeneral,females(n)=females(n-1)+females(n-2)◦ Everyfemalealiveatmonthn-2willproduceonefemaleinmonthn;
◦ Thesecanbeaddedthosealiveinmonthn-1togettotalaliveinmonthn
Month Females
0 1
1 1
2 2
3 3
4 5
5 8
6 13
6.0001LECTURE6 32
![Page 33: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/33.jpg)
FIBONACCI §Basecases:◦ Females(0)=1◦ Females(1)=1
§Recursivecase◦ Females(n)=Females(n-1)+Females(n-2)
6.0001LECTURE6 33
![Page 34: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/34.jpg)
6.0001LECTURE6 34
FIBONACCI def fib(x):
"""assumes x an int >= 0
returns Fibonacci of x""”
if x == 0 or x == 1:
return 1
else:
return fib(x-1) + fib(x-2)
![Page 35: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/35.jpg)
RECURSION ON NON-NUMERICS § howtocheckifastringofcharactersisapalindrome,i.e.,readsthesameforwardsandbackwards◦ “AblewasI,ereIsawElba”–avributedtoNapoleon◦ “Arewenotdrawnonward,wefew,drawnonwardtonewera?”–avributedtoAnneMichaels
35
Image courtesy of wikipedia, in the public domain. By Larth_Rasnal (Own work) [GFDL (https://www.gnu.org/licenses/fdl-1.3.en.html) or CC BY 3.0 (https://creativecommons.org/licenses/by/3.0)], via Wikimedia Commons.
6.0001LECTURE6
![Page 36: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/36.jpg)
SOLVING RECURSIVELY? §First,convertthestringtojustcharacters,bystrippingoutpunctuaSon,andconverSnguppercasetolowercase
§Then◦ Basecase:astringoflength0or1isapalindrome◦ Recursivecase:◦ Iffirstcharactermatcheslastcharacter,thenisapalindromeifmiddlesecSonisapalindrome
6.0001LECTURE6 36
![Page 37: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/37.jpg)
EXAMPLE § ‘AblewasI,ereIsawElba’à‘ablewasiereisawleba’
§ isPalindrome(‘ablewasiereisawleba’)issameas◦ ‘a’ == ‘a’ andisPalindrome(‘blewasiereisawleb’)
6.0001LECTURE6 37
![Page 38: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/38.jpg)
6.0001LECTURE6 38
def isPalindrome(s):
def toChars(s):s = s.lower()ans = ''for c in s:
if c in 'abcdefghijklmnopqrstuvwxyz':ans = ans + c
return ans
def isPal(s):if len(s) <= 1:
return Trueelse:
return s[0] == s[-1] and isPal(s[1:-1])
return isPal(toChars(s))
![Page 39: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/39.jpg)
DIVIDE AND CONQUER §anexampleofa“divideandconquer”algorithm
§solveahardproblembybreakingitintoasetofsub-problemssuchthat:◦ sub-problemsareeasiertosolvethantheoriginal◦ soluSonsofthesub-problemscanbecombinedtosolvetheoriginal
6.0001LECTURE6 39
![Page 40: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/40.jpg)
DICTIONARIES
6.0001LECTURE6 40
![Page 41: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/41.jpg)
HOW TO STORE STUDENT INFO §sofar,canstoreusingseparatelistsforeveryinfonames = ['Ana', 'John', 'Denise', 'Katy']
grade = ['B', 'A+', 'A', 'A']
course = [2.00, 6.0001, 20.002, 9.01]
§aseparatelistforeachitem§eachlistmusthavethesamelength§infostoredacrosslistsatsameindex,eachindexreferstoinfoforadifferentperson
6.0001LECTURE6 41
![Page 42: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/42.jpg)
HOW TO UPDATE/RETRIEVE STUDENT INFO def get_grade(student, name_list, grade_list, course_list):
i = name_list.index(student)
grade = grade_list[i]
course = course_list[i]
return (course, grade)
§messyifhavealotofdifferentinfotokeeptrackof
§mustmaintainmanylistsandpassthemasarguments
§mustalwaysindexusingintegers
§mustremembertochangemulSplelists6.0001LECTURE6 42
![Page 43: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/43.jpg)
A BETTER AND CLEANER WAY – A DICTIONARY §nicetoindexitemofinterestdirectly(notalwaysint)
§nicetouseonedatastructure,noseparatelists
Alist Adic0onary
Elem1
Elem2
Elem3
Elem4
…
Key1
Key2
Key3
Key4
…
Val1
Val2
Val3
Val4
…
0
1
2
3
…
6.0001LECTURE6 43
![Page 44: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/44.jpg)
A PYTHON DICTIONARY §storepairsofdata
• key• value
my_dict = {}
grades = {'Ana':'B', 'John':'A+', 'Denise':'A', 'Katy':'A'}
Key1
Key2
Key3
…
Val1
Val2
Val3
…
key1val1 key2val2 key3val3 key4val4
6.0001LECTURE6 44
'Ana'
'Denise'
'John'
'Katy'
'B'
'A'
'A+'
'A'
![Page 45: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/45.jpg)
'Ana'
'Denise'
'John'
'Katy'
'B'
'A'
'A+'
DICTIONARY LOOKUP §similartoindexingintoalist
§looksupthekey
§returnsthevalueassociatedwiththekey 'A'
§ifkeyisn’tfound,getanerror
grades = {'Ana':'B', 'John':'A+', 'Denise':'A', 'Katy':'A'}
grades['John'] à evaluatesto'A+'
grades['Sylvan'] à givesaKeyError
6.0001LECTURE6 45
![Page 46: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/46.jpg)
DICTIONARY OPERATIONS
grades = {'Ana':'B', 'John':'A+', 'Denise':'A', 'Katy':'A'}
§addanentrygrades['Sylvan'] = 'A'
§testifkeyindicSonary'John' in grades à returns True
'Daniel' in grades à returns False
§deleteentrydel(grades['Ana'])
6.0001LECTURE6 46
'Sylvan' 'A'
'Ana'
'Denise'
'John'
'Katy'
'B'
'A'
'A+'
'A'
![Page 47: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/47.jpg)
DICTIONARY OPERATIONS
grades = {'Ana':'B', 'John':'A+', 'Denise':'A', 'Katy':'A'}
§getaniterablethatactslikeatupleofallkeys grades.keys() à returns ['Denise','Katy','John','Ana']
§getaniterablethatactslikeatupleofallvaluesgrades.values() à returns ['A', 'A', 'A+', 'B']
6.0001LECTURE6 47
'Ana'
'Denise'
'John'
'Katy'
'B'
'A'
'A+'
'A'
![Page 48: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/48.jpg)
DICTIONARY KEYS and VALUES §values
• anytype(immutableandmutable)• canbeduplicates• dicSonaryvaluescanbelists,evenotherdicSonaries!
§keys• mustbeunique• immutabletype(int,float,string,tuple,bool)
• actuallyneedanobjectthatishashable,butthinkofasimmutableasallimmutabletypesarehashable
• carefulwithfloattypeasakey
§noordertokeysorvalues!d = {4:{1:0}, (1,3):"twelve", 'const':[3.14,2.7,8.44]}
6.0001LECTURE6 48
![Page 49: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/49.jpg)
list vs dict
6.0001LECTURE6 49
§orderedsequenceof §matches“keys”toelements “values”
§lookupelementsbyan §lookuponeitembyintegerindex anotheritem
§indiceshaveanorder §noorderisguaranteed
§indexisaninteger §keycanbeanyimmutabletype
![Page 50: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/50.jpg)
EXAMPLE: 3 FUNCTIONS TO ANALYZE SONG LYRICS 1)createafrequencydic0onarymappingstr:int
2)findwordthatoccursthemostandhowmanySmes• usealist,incasethereismorethanoneword• returnatuple(list,int)for(words_list,highest_freq)
3)findthewordsthatoccuratleastX0mes• letuserchoose“atleastXSmes”,soallowasparameter• returnalistoftuples,eachtupleisa(list, int)containingthelistofwordsorderedbytheirfrequency
• IDEA:FromsongdicSonary,findmostfrequentword.Deletemostcommonword.Repeat.Itworksbecauseyouare
gdicSonary.
6.0001LECTURE6 50
mutaSngtheson
![Page 51: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/51.jpg)
CREATING A DICTIONARY def lyrics_to_frequencies(lyrics): myDict = {}
for word in lyrics:
if word in myDict:
myDict[word] += 1
else:
myDict[word] = 1
return myDict
6.0001LECTURE6 51
![Page 52: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/52.jpg)
USING THE DICTIONARY def most_common_words(freqs):
values = freqs.values()
best = max(values)
words = []
for k in freqs:
if freqs[k] == best:
words.append(k)
return (words, best)
6.0001LECTURE6 52
![Page 53: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/53.jpg)
LEVERAGING DICTIONARY PROPERTIES def words_often(freqs, minTimes): result = [] done = False while not done:
temp = most_common_words(freqs)if temp[1] >= minTimes:
result.append(temp)for w in temp[0]:
del(freqs[w])else:
done = True return result
print(words_often(beatles, 5))
6.0001LECTURE6 53
![Page 54: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/54.jpg)
FIBONACCI RECURSIVE CODE def fib(n):
if n == 1:
return 1
elif n == 2:
return 2
else:
return fib(n-1) + fib(n-2)
§twobasecases§callsitselftwice§thiscodeisinefficient
6.0001LECTURE6 54
![Page 55: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/55.jpg)
INEFFICIENT FIBONACCI fib(n) = fib(n-1) + fib(n-2)
§recalcula0ngthesamevaluesmanySmes!§couldkeeptrackofalreadycalculatedvalues
6.0001LECTURE6 55
fib(5)
fib(4) fib(3)
fib(3) fib(2) fib(1)
fib(2) fib(1)
fib(2)
![Page 56: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/56.jpg)
FIBONACCI WITH A DICTIONARY def fib_efficient(n, d): if n in d:
return d[n] else:
ans = fib_efficient(n-1, d) + fib_efficient(n-2, d)d[n] = ansreturn ans
d = {1:1, 2:2}print(fib_efficient(6, d))
§doalookupfirstincasealreadycalculatedthevalue§modifydic0onaryasprogressthroughfuncSoncalls
6.0001LECTURE6 56
![Page 57: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/57.jpg)
EFFICIENCY GAINS § Callingfib(34)resultsin11,405,773recursivecallstotheprocedure§ Callingfib_efficient(34)resultsin65recursivecallstotheprocedure§UsingdicSonariestocaptureintermediateresultscanbeveryefficient§Butnotethatthisonlyworksforprocedureswithoutsideeffects(i.e.,theprocedurewillalwaysproducethesameresultforaspecificargumentindependentofanyothercomputaSonsbetweencalls)
6.0001LECTURE6 57
![Page 58: MIT6 0001F16 Recursion, Dictionaries - MIT OpenCourseWare · PDF fileRECURSION, DICTIONARIES ... fact Some code fact scope (call w/ n=4) n 4 ... if c in 'abcdefghijklmnopqrstuvwxyz':](https://reader031.fdocuments.us/reader031/viewer/2022022500/5aa28b637f8b9a1f6d8d616b/html5/thumbnails/58.jpg)
MIT OpenCourseWarehttps://ocw.mit.edu
6.0001 Introduction to Computer Science and Programming in PythonFall 2016
For information about citing these materials or our Terms of Use, visit: https://ocw.mit.edu/terms.