teach a level compu/ng: algorithms and data structures · 2017. 3. 8. · 08/03/2017 1 teach a...
TRANSCRIPT
08/03/2017
1
Teach A level Compu/ng: Algorithms and Data
Structures
EliotWilliams
@MrEliotWilliams
Course Outline
1 Representa9onsofdatastructures:Arrays,tuples,Stacks,Queues,Lists
2 RecursiveAlgorithms(&listsaswedidn’tquitegettherelast9me…)
3 SearchingandSor9ng-EWwillbelate!
4 HashingandDic9onaries,GraphsandTrees
5 Depthandbreadthfirstsearching;treetraversals
08/03/2017
2
Procedures Towriterecursiveprogramsweneedagoodunderstandingof
procedures
Why Procedures?
• Codeorganisa9on• Proceduresallowcodetobeorganisedinparts• Top-downdevelopment
• Codereuse• Thelibrary• Procedureswithparameters:exis9ngcode,yourdata
• Recursion
08/03/2017
3
• Procedures:• 0ormoreinputs• 0ormoreoutputs• Sideeffects(printstatements,globalvariablesetc)
• Func9ons• 1ormoreinputs• 1output• Nosideeffects
Procedures & Func/ons
Crea/ng a procedure in python
• Whatistheresult?• Isvariableachanged?
def fun1(p):! p = p + 1! return p!!a = 1!b = fun1(a)!print("argument a =", a)!print("return value b =", b)!
Name
Parameter
Returnexpression
Func9oncall
Argument
08/03/2017
4
Procedures Call Tree • Onefunc9oncallsanother
def doub(p):! return p*2!!def quad(p):! d = doub(p)! return doub(d)!!n = int(input("Number: "))!print("4 x", n, "=", quad(n))!
main
quad
doub
call
call return
return
Procedures Scope • Scope:dic9onaryofvariables
def doub(p):! return p*2!!def quad(p):! d = doub(p)! return doub(d)!!n = int(input("Number: "))!print("4 x", n, "=", quad(n))!
nàinteger(3)doubà…codequadà…code
pàinteger(3)dàinteger(6)
pàinteger(6)
08/03/2017
5
• Whatistheresult?• Isthelistvariableachanged?
deffun1(thelist):thelist.append(41)myl=[2,3,4]fun1(myl)print("myl=",myl)
Pass by reference or by value
Justlikeassignmentalist:…variablereferstothelist…parameterreferstothelistNoglobal:referenceisreadAnymutableobjectwillwillbehavethisway…….
big
• Defineafunc9onbigthattakes2inputsandreturnsthebiggest!
defbig(a,b):ifprint(big(2,3))print(big(4,4))
08/03/2017
6
big
• Defineafunc9onbigthattakes2inputsandreturnsthebiggest!
defbig(a,b):ifa>b:returnareturnbprint(big(2,3))print(big(4,4))
big3
defbig3(a,b,c):ifa>b:ifa>c:returnaelse:returncelse:ifb>c:returnbelse:returnc
defbig(a,b):ifa>b:returnareturnb
defbig3(a,b,c):d=big(a,b)returnbig(d,c)
08/03/2017
7
Recursion Recursion
Recursion
• Recursionincomputerscienceisamethodwherethesolu9ontoaproblemdependsonsolu9onstosmallerinstancesofthesameproblem(asopposedtoitera9on).[1]Theapproachcanbeappliedtomanytypesofproblems,andrecursionisoneofthecentralideasofcomputerscience.[2]
08/03/2017
8
What do you need to write every possible computer program….. • Complexques9on–Babbage'sanaly9calEnginehad:• Thearithme9cfunc9ons+,−,×where−indicates"proper"subtrac9onx−y=0ify≥x• Anysequenceofopera9onsisanopera9on• Itera9onofanopera9on(repea9ngn9mesanopera9onP)• Condi9onalitera9on(repea9ngn9mesanopera9onPcondi9onalonthe"success"oftestT)• Condi9onaltransfer(i.e.condi9onal"goto").
• Anotheranswerisprocedures,simplearithme9cwiththecomparisons,and"if"statements
Predict & Explain what will this do
importturtle
myTurtle=turtle.Turtle()
myWindow=turtle.Screen()
deffoo(bar):
ifbar>0:
myTurtle.forward(bar)
myTurtle.right(90)
foo(bar-5)
foo(100)
myWindow.exitonclick()
08/03/2017
9
Our first Example - Spiral
importturtle
myTurtle=turtle.Turtle()
myWindow=turtle.Screen()
defspiral(side):
ifside>0:
myTurtle.forward(side)
myTurtle.right(90)
spiral(side-5)
spiral(100)
myWindow.exitonclick()
Modify
• Changetheanglebetweenthebranches• ChangethethicknessofthebranchessothatasthebranchLengetssmaller,thelinegetsthinner.• ChangethecolourofthebranchessothattheystartbrownandasthebranchLengetsveryshortitisgreen.• ChangetherecursivecallbranchLensothatinsteadofalwayssubtrac9ngthesameamountyousubtractarandomamountinsomerange
Hints:turtle.width(width)turtle.color(“blue”)
08/03/2017
10
Our first recursive program: Factorial
• Inmyopinionnumbersequencestendtobetoocomplexforafirstexample• Recursionisathresholdconcept• Newconcept• Differentwayofthinkingaboutrepe99on• Newterminology
• Wewanttokeepitsimpleatfirst• Cogni9veloadtheory
Our first recursive program
defwibbler():print("wibble“)returnwibbler()
wibbler()#whatsgoingtohappen?
• what'sgoingtohappen?
• Doesthisworklikealoop?• Whattypeofloopdoesitworklike?
08/03/2017
11
A slight modifica/on
defwibbler(n):print("Wibble",n)returnwibbler(n+1)print(wibbler(1))
• Howmany9mesdoesitrun?
An improved wibbler……
defwibbler(n):if(n>0):print("wibble")returnwibbler(n-1)wibbler(3)
• What’sgoingtohappen
• Whatloopstructureisthislike?
08/03/2017
12
What's the difference?
defwibbler(n):if(n>0):print("wibble")returnwibbler(n-1)
defwibble(n):if(n==1): return("wibble")return("wibble"+wibble(n-1))
What's the difference?
defwibbler(n):if(n>0):print("wibble")returnwibbler(n-1)wibbler(3)
defwibble(n):if(n==1): return("wibble")return("wibble"+wibble(n-1))
print(wibble(3))
08/03/2017
13
defwibble(n):if(n==1): return("wibble")return("wibble"+wibble(n-1))
• Definesomethingintermsofitself• RecursiveCase–simplifiestheproblemandmovestowardsthebasecasewitharecursivecall• BaseCase–smallestinstance(Youmayneedmorethanonebasecase)
BaseCase–stopcondi9onRecursiveCase
Task - allstar
• Givenastring,computerecursivelyanewstringwherealltheadjacentcharsarenowseparatedbya"*".
• allStar("hello")→"h*e*l*l*o"• allStar("ab")→"a*b"• allStar("a")→"a"Iden9fyawaytobreakaproblemuprecursively….LookforaRecursiveCaseandaBaseCasedefallStar(string):
if(??????): return???????return(?????????????)
08/03/2017
14
Task /me
• Reverse
What's going on………………………….
Achildcouldn'tsleep,sohermothertoldherastoryaboutalizlefrog,whocouldn'tsleep,sothefrog'smothertoldherastoryaboutalizlebear,
whocouldn'tsleep,sothebear'smothertoldherastoryaboutalizleweasel...
whofellasleepandthelizlebearfellasleep;
andthelizlefrogfellasleep;andthechildfellasleep.
08/03/2017
15
• f(n)=n*f(n-1)• f(1)=1
• f(4)=4*f(3)f(3)=3*3f(3)=3*f(2)
Factorial revisted
f(2)=2*f(1)
f(1)=1
• f(n)=n*f(n-1)• f(1)=1
• f(4)=4*f(3)f(3)=3*3f(3)=3*f(2)
Factorial revisted
f(2)=2*1
08/03/2017
16
• f(n)=n*f(n-1)• f(1)=1
• f(4)=4*f(3)f(3)=3*3f(3)=3*f(2)
Factorial revisted
f(2)=2
• f(n)=n*f(n-1)• f(1)=1
• f(4)=4*f(3)f(3)=3*3f(3)=3*2
Factorial revisted
08/03/2017
17
• f(n)=n*f(n-1)• f(1)=1
• f(4)=4*f(3)f(3)=3*3f(3)=6
Factorial revisted
• f(n)=n*f(n-1)• f(1)=1
• f(4)=4*6
Factorial revisited
08/03/2017
18
• f(n)=n*f(n-1)• f(1)=1
• f(4)=24
Factorial revisted
Why use recursion
• Recursionisamethodofsolvingproblemsbasedonthedivideandconquermentality• Some9mesitseasiertosolvethinkofaproblemintermsofitself
• Q:Doesusingrecursionusuallymakeyourcodefaster?• A:No.• Q:Doesusingrecursionusuallyuselessmemory?• A:No.• Q:Thenwhyuserecursion?• A:Itsome9mesmakesyourcodemuchsimpler!
08/03/2017
19
Predict-Explain-Modify-Create
• Predict–givenaworkingprogram,whatdoyouthinkitwilldo?(atahighlevelofabstrac9on)• Run–runitandtestyourpredic9on• Explain/Ar9culate–getintothenizygrizy.Whatdoeseachlineofcodemean?(lowlevelofabstrac9on).Lotsofac9vi9eshere:trace,annotate,explain,talkabout,iden9fyparts,etc….• Modify–edittheprogramtomakeitdodifferentthings(highandlowlevelsofabstrac9on)Design/Create–designanewprogramthatusesthesamenizygrizybutthatsolvesanewproblem.
Linked Lists Animplementa9onofthelistabstrac9ons
08/03/2017
20
Linked List Concept
• Eachentryhas• Avalue• Apointertothenextentry
• Keepapointertothefrontentry• ThepointerofthelastentryisNone
b c d e f
front back
• Wecouldrepresentthisinpythonby• list=[['James',2],['Bob',0],['Sarah',-1]]• startpos=1• length=3
• Wewouldneedproceduresto• findavaluesposi9on• Findanpointersposi9on• Add• Delete(andupdatethepreviouspointer–usingfindapointer)• Printinorder• Insertanewvalue
08/03/2017
21
Exercise
• Redrawlista|er:• appendinganewentryattheend• inser9ngbeforeentryzero• inser9ngbeforeentry3
b c d e f
front back
Linked List Index
• Countalongthelisttoentryi• Returnthevalue
pointer = front count = 0 while count < i: pointer ß next of current entry count = count + 1 return the value of current entry
myList.index(i)
08/03/2017
22
Linked List Update
• Countalongthelisttoentryindex• Replacevaluewithnewvalue
pointer = front count = 0 while count < idx: pointer ß next of currentEntry count = count = 1 currentEntry.value = newValue
myList.update(idx, newValue)
Linked List Insert
• Countalongthelisttoentryidx-1• Insertanewentry• Nextpointerofcurrententrypointstonewentry• Nextpointerofnewentrypointstofollowingentry
myList.insert(idx, newValue)