c# display pdf in browser : Add page number to pdf file control SDK system web page winforms azure console python-programming-an-introduction-to-computer-science23-part385

12.5. EXERCISES
223
Wecouldhaveusedinheritancetobuildourpokerprogram. WhenwefirstwrotetheDieViewclass,
itdidnotprovideawayofchangingtheappearanceofthedie. Wesolvedthisproblembymodifyingthe
originalclassdefinition. Analternativewouldhavebeentoleavetheoriginalclassunchangedandcreate
anewsubclassColorDieView. AColorDieViewisjustlikeaDieViewexceptthatitcontainsan
additionalmethodthatallowsustochangeitscolor.HereishowitwouldlookinPython:
class ColorDieView(DieView):
def setValue(self, , value):
self.value = = value
DieView.setValue(self, value)
def setColor(self, , color):
self.foreground = = color
self.setValue(self.value)
Thefirstlineofthisdefinitionsaysthatwearedefininganewclass ColorDieViewthatisbased
on(i.e., asubclassof)DieView. . Inside e thenewclass, wedefinetwomethods. . Thesecondmethod,
setColor,addsthenewoperation.Ofcourse,inordertomakesetColorwork,wealsoneedtomodify
thesetValueoperationslightly.
ThesetValuemethodinColorDieViewredefinesoroverridesthedefinitionofsetValuethatwas
providedintheDieViewclass.ThesetValuemethodinthenewclassfirststoresthevalueandthenrelies
onthesetValuemethodofthesuperclassDieViewtoactuallydrawthepips.Noticeespeciallyhowthe
calltothemethodfromthesuperclassismade.Thenormalapproachself.setValue(value)wouldre-
fertothesetValuemethodoftheColorDieViewclass,sinceselfisaninstanceofColorDieView.
InordertocalltheoriginalsetValuemethodfromthesuperclass,itisnecessarytoputtheclassname
wheretheobjectwouldnormallygo.
DieView.setValue(self,value)
Theactualobjecttowhichthemethodisappliedisthensentasthefirstparameter.
12.5 Exercises
1. Inyourownwords,describetheprocessofOOD.
2. Inyourownwords,defineencapsulation,polymorphismandinheritance.
3. AddbellsandwhistlestothePokerDicegame.
4. RedoanyofthedesignproblemsfromChapter9usingOOtechniques.
5. Findtherulestoaninterestingdicegameandwriteaninteractiveprogramtoplayit. . Someexamples
areCraps,Yacht,GreedandSkunk.
6. Writeaprogramthatdealsfourbridgehands,countshowmanypointstheyhaveandgivesopening
bids.
7. Findasimplecardgamethatyoulikeandimplementaninteractiveprogramtoplaythatgame.Some
possibilitiesareWar,Blackjack,varioussolitairegames,andCrazyEights.
8. Writeaninteractiveprogramforaboardgame. SomeexamplesareOthello(Reversi),ConnectFour,
Battleship,Sorry!,andParcheesi.
Add page number to pdf file - insert pages into PDF file in C#.net, ASP.NET, MVC, Ajax, WinForms, WPF
Guide C# Users to Insert (Empty) PDF Page or Pages from a Supported File Format
add page pdf; add page number to pdf online
Add page number to pdf file - VB.NET PDF Page Insert Library: insert pages into PDF file in vb.net, ASP.NET, MVC, Ajax, WinForms, WPF
Easy to Use VB.NET APIs to Add a New Blank Page to PDF Document
adding a page to a pdf in reader; add page to pdf in preview
224
CHAPTER12. OBJECT-ORIENTEDDESIGN
C# PDF File Split Library: Split, seperate PDF into multiple files
If your page number is set as 1, then the two output PDF files will contains the first page and the later three pages Add necessary references:
add page number to pdf print; add a page to pdf file
VB.NET PDF File Split Library: Split, seperate PDF into multiple
can split target multi-page PDF document file to one-page PDF files or PDF file to smaller PDF documents by every given number of pages Add necessary references
add page pdf reader; add page numbers to pdf preview
Chapter13
AlgorithmAnalysisandDesign
Ifyouhaveworkedyourwaythroughtothispointinthebook,youarewellonthewaytobecominga
programmer. WaybackinChapter1,Idiscussedtherelationshipbetweenprogrammingandthestudyof
computerscience. Nowthatyouhavesomeprogrammingskills, , youarereadytostartconsideringthe
broaderissuesinthefield.Herewewilltakeuponeofthecentralissues,namelythedesignandanalysisof
algorithms.
13.1 Searching
Let
'
sbeginbyconsideringaverycommonandwell-studiedprogrammingproblem: search. Searchisthe
processoflookingforaparticularvalueinacollection.Forexample,aprogramthatmaintainsthemember-
shiplistforaclubmightneedtolookuptheinformationaboutaparticularmember.Thisinvolvessomeform
ofsearchprocess.
13.1.1 ASimpleSearchingProblem
Tomakethediscussionofsearchingalgorithmsas simpleaspossible, let
'
sboiltheproblemdowntoits
essentialessence.Hereisthespecificationofasimplesearchingfunction:
def search(x, , nums):
# nums is s a a list of numbers and x is a number
# RETURNS S the e position in the list where x x occurs s or -1 if
#
x is not t in n the list.
Hereareacoupleinteractiveexamplesthatillustrateitsbehavior:
>>> search(4, , [3, , 1, 4, 2, 5])
2
>>> search(7, , [3, , 1, 4, 2, 5])
-1
Inthefirstexample,thefunctionreturnstheindexwhere4appearsinthelist. Inthesecondexample,the
returnvalue-1indicatesthat7isnotinthelist.
YoumayrecallfromourdiscussionoflistoperationsthatPythonactuallyprovidesanumberofbuilt-in
search-relatedmethods.Forexample,wecantesttoseeifavalueappearsinasequenceusingin.
if x in nums:
# do something
Ifwewanttoknowthepositionofxinalist,theindexmethodfillsthebillnicely.
225
C# PDF insert text Library: insert text into PDF content in C#.net
pageIndex, The page index of the PDF page that will be 0
add page numbers to pdf document in preview; adding pages to a pdf
C# PDF File & Page Process Library SDK for C#.net, ASP.NET, MVC
Highlight Text. Add Text. Add Text Box. Drawing Markups. PDF users to do multiple manipulations on PDF file and page Please note that, PDF page number starts from
adding page numbers to pdf document; adding page numbers to pdf in reader
226
CHAPTER13. ALGORITHMANALYSISANDDESIGN
>>> nums = [3,1,4,2,5]
>>> nums.index(4)
2
Infact,theonlydifferencebetweenoursearchfunctionandindexisthatthelatterraisesanexceptionif
thetargetvaluedoesnotappearinthelist.Wecouldimplementthesearchfunctionusingindexbysimply
catchingtheexceptionandreturning-1forthatcase.
def search(x, , nums):
try:
return nums.index(x)
except:
return -1
Thisapproachbegsthequestion,however.TherealissueishowdoesPythonactuallysearchthelist?What
isthealgorithm?
13.1.2 Strategy1:LinearSearch
Let
'
stryourhandatdevelopingasearchalgorithmusingasimple“bethecomputer”strategy.Supposethat
Igaveyouapagefullofnumbersinnoparticularorderandaskedwhetherthenumber13isinthelist.How
wouldyousolvethisproblem?Ifyouarelikemostpeople,youwouldsimplyscandownthelistcomparing
eachvalueto13. Whenyousee13inthelist,youquitandtellmethatyoufoundit. Ifyougettothevery
endofthelistwithoutseeing13,thenyoutellmeit
'
snotthere.
Thisstrategyiscalledalinearsearch. Youaresearchingthroughthelistofitemsonebyoneuntilthe
targetvalueisfound.Thisalgorithmtranslatesdirectlyintosimplecode.
def search(x, , nums):
for i in range(len(nums)):
if nums[i] ] == = x:
# item found, return n the e index value
return i
return -1
# loop finished, , item m was not in list
Thisalgorithmwasnothardtodevelop, anditwillworkverynicelyformodest-sizedlists. . Foran
unorderedlist,thisalgorithmisasgoodasany.ThePythoninandindexoperatorsbothimplementlinear
searchingalgorithms.
Ifwehaveaverylargecollectionofdata,wemightwanttoorganizeitinsomewaysothatwedon
'
thave
tolookateverysingleitemtodeterminewhere,orif,aparticularvalueappearsinthelist.Supposethatthe
listisstoredinsortedorder(lowesttohighest).Assoonasweencounteravaluethatisgreaterthanthetarget
value,wecanquitthelinearsearchwithoutlookingattherestofthelist.Onaverage,thatsavesusabouthalf
ofthework.But,ifthelistissorted,wecandoevenbetterthanthis.
13.1.3 Strategy2:BinarySearch
Whenalistisordered,thereisamuchbettersearchingstrategy,onethatyouprobablyalreadyknow.Have
youeverplayedthenumberguessinggame?Ipickanumberbetween1and100,andyoutrytoguesswhat
itis.Eachtimeyouguess,Iwilltellyouifyourguessiscorrect,toohigh,ortoolow.Whatisyourstategy?
Ifyouplaythisgamewithaveryyoungchild, theymightwelladopta strategyofsimplyguessing
numbersatrandom. Anolderchildmightemployasystematicapproachcorrespondingtolinearsearch,
guessing1
2
3
4
untilthemysteryvalueisfound.
Ofcourse,virtuallyanyadultwillfirstguess50. Iftoldthatthenumberishigher,thentherangeof
possiblevaluesis50–100. Thenextlogicalguessis75. Eachtimeweguessthemiddleoftheremaining
rangetotrytonarrowdownthepossiblerange. Thisstrategyiscalledabinarysearch. Binarymeanstwo,
andateachstep,wearedividingthepossiblerangeintotwoparts.
Wecanemployabinarysearchstrategytolookthroughasortedlist. Thebasicideaisthatweusetwo
variablestokeeptrackoftheendpointsoftherangeinthelistwheretheitemcouldbe. Initially,thetarget
C# PDF Text Search Library: search text inside PDF file in C#.net
Add necessary references: Description: Search specified string from all the PDF pages. eg: The first page is 0. 0
add page numbers to a pdf file; add and delete pages in pdf online
C# PDF delete text Library: delete, remove text from PDF file in
Add necessary references: RasterEdge.Imaging.Basic.dll. matchString, The string wil be deleted from PDF file, -. 0
adding page numbers to pdf files; add and remove pages from a pdf
13.1. SEARCHING
227
couldbeanywhereinthelist,sowestartwithvariableslowandhighsettothefirstandlastpositionsof
thelist,respectively.
Theheartofthealgorithmisaloopthatlooksattheiteminthemiddleoftheremainingrangetocompare
ittox. Ifxissmallerthanthemiddleitem,thenwemovetop,sothatthesearchisnarrowedtothelower
half. Ifxislarger,thenwemovelow,andthesearchisnarrowedtotheupperhalf. . Theloopterminates
whenxisfoundortherearenolongeranymoreplacestolook(i.e.,low > high).Hereisthecode.
def search(x, , nums):
low = 0
high = len(nums) ) - - 1
while low w <= = high:
# There is still l a a range to search
mid = (low + high) / 2
# position of f middle e item
item = nums[mid]
if x == item :
# Found it! Return n the e index
return mid
elif x < < item:
# x is in lower r half f of range
high = = mid d - 1
#
move top p marker r down
else:
# x is in upper half
low = mid + 1
#
move bottom m marker r up
return -1
# no range left t to o search, x is not there
Thisalgorithmisquiteabitmoresophisticatedthanthesimplelinearsearch. Youmightwanttotrace
throughacoupleofexamplesearchestoconvinceyourselfthatitactuallyworks.
13.1.4 ComparingAlgorithms
Sofar,wehavedevelopedtwosolutionstooursimplesearchingproblem. Whichoneisbetter? Well,that
dependsonwhatexactlywemeanbybetter. Thelinearsearchalgorithmismucheasiertounderstandand
implement. Ontheotherhand,weexpectthatthebinaryseachismoreefficient,becauseitdoesn
'
thaveto
lookateveryvalueinthelist. Intuitively,then,wemightexpectthelinearsearchtobeabetterchoicefor
smalllistsandbinarysearchabetterchoiceforlargerlists.Howcouldweactuallyconfirmsuchintuitions?
Oneapproachwouldbetodoanempiricaltest. Wecouldsimplycodeupbothalgorithmsandtrythem
outonvarioussizedlists toseehowlongthesearchtakes. . Thesealgorithmsarebothquiteshort,soit
wouldnotbedifficulttorunafewexperiments. WhenItestedthealgorithmsonmyparticularcomputer(a
somewhatdatedlaptop),linearsearchwasfasterforlistsoflength10orless,andtherewasnosignificant
differenceintherangeoflength10–1000.Afterthat,binarysearchwasaclearwinner.Foralistofamillion
elements,linearsearchaveraged2.5secondstofindarandomvalue,whereasbinarysearchaveragedonly
0.0003seconds.
Theempiricalanalysishasconfirmedourintuition, buttheseareresultsfromoneparticularmachine
underspecificcircumstances(amountofmemory,processorspeed,currentload,etc.). Howcanwebesure
thattheresultswillalwaysbethesame?
Anotherapproachistoanalyzeouralgorithmsabstractlytoseehowefficienttheyare.Otherfactorsbeing
equal,weexpectthealgorithmwiththefewestnumberof“steps”tobethemoreefficient. Buthowdowe
countthenumberofsteps?Forexample,thenumberoftimesthateitheralgorithmgoesthroughitsmainloop
willdependontheparticularinputs. Wehavealreadyguessedthattheadvantageofbinarysearchincreases
asthesizeofthelistincreases.
Computerscientistsattacktheseproblemsbyanalyzingthenumberofstepsthatanalgorithmwilltake
relativetothesizeordifficultyofthespecificprobleminstancebeingsolved.Forsearching,thedifficultyis
determinedbythesizeofthecollection.Obviously,ittakesmorestepstofindanumberinacollectionofa
millionthanitdoesinacollectionoften.Thepertinentquestionishowmanystepsareneededtofindavalue
inalistofsizen.Weareparticularlyinterestedinwhathappensasngetsverylarge.
Let
'
sconsiderthelinearsearchfirst. Ifwehavealistoftenitems,themostworkouralgorithmmight
havetodoistolookateachiteminturn.Theloopwilliterateatmosttentimes.Supposethelististwiceas
big. Thenwemighthavetolookattwiceasmanyitems.Ifthelististhreetimesaslarge,itwilltakethree
C# PDF Text Highlight Library: add, delete, update PDF text
200F); annot.EndPoint = new PointF(300F, 400F); // add annotation to The string wil be highlighted from PDF file, 0
add pages to pdf file; adding a page to a pdf file
C# Word - Split Word Document in C#.NET
your page number is set as 1, then the two output Word files will contains the first page and the later three pages respectively. C# DLLs: Split Word File. Add
add pages to pdf reader; adding page numbers to pdf in
228
CHAPTER13. ALGORITHMANALYSISANDDESIGN
timesaslong,etc.Ingeneral,theamountoftimerequiredislinearlyrelatedtothesizeofthelistn.Thisis
whatcomputerscientistscallalineartimealgorithm.Nowyoureallyknowwhyit
'
scalledalinearsearch.
Whataboutthebinarysearch?Let
'
sstartbyconsideringaconcreteexample. Supposethelistcontains
sixteenitems.Eachtimethroughtheloop,theremainingrangeiscutinhalf.Afteronepass,thereareeight
itemslefttoconsider. Thenexttimethroughtherewillbefour,thentwo,andfinallyone.Howmanytimes
willtheloopexecute?Itdependsonhowmanytimeswecanhalvetherangebeforerunningoutofdata.This
tablemighthelpyoutosortthingsout:
Listsize Halvings
1
0
2
1
4
2
8
3
16
4
Canyouseethepatternhere? Eachextraiterationoftheloopdoublesthesizeofthelist. Ifthebinary
searchloopsitimes,itcanfindasinglevalueinalistofsize2
i
. Eachtimethroughtheloop,itlooksat
onevalue(themiddle)inthelist. Toseehowmanyitemsareexaminedinalistofsizen,weneedtosolve
thisrelationship:n
2
i
fori. Inthisformula,iisjustanexponentwithabaseof2. Usingtheappropriate
logarithmgivesusthisrelationship: i
log
2
n. Ifyouarenotentirelycomfortablewithlogarithms,just
rememberthatthisvalueisthenumberoftimesthatacollectionofsizencanbecutinhalf.
OK,sowhatdoesthisbitofmathtellus? Binarysearchisanexampleofalogtimealgorithm. . The
amountoftimeittakestosolveagivenproblemgrowsasthelogoftheproblemsize. Inthecaseofbinary
search,eachadditionaliterationdoublesthesizeoftheproblemthatwecansolve.
Youmightnotappreciatejusthowefficientbinarysearchreallyis. Letmetrytoputitinperspective.
SupposeyouhaveaNewYorkCityphonebookwith,say,twelvemillionnameslistedinalphabeticalorder.
YouwalkuptoatypicalNewYorkeronthestreetandmakethefollowingproposition(assumingtheirnumber
islisted):I
'
mgoingtotryguessingyourname. EachtimeIguessaname,youtellmeifyournamecomes
alphabeticallybeforeorafterthenameIguess.Howmanyguesseswillyouneed?
Ouranalysisaboveshowstheanswertothisquestionislog
2
12
000
000.Ifyoudon
'
thaveacalculator
handy,hereisaquickwaytoestimatetheresult.2
10
1024orroughly1000,and1000x1000
1
000
000.
Thatmeansthat2
10
x2
10
2
20
1
000
000. Thatis,2
20
isapproximatelyonemillion. So,searchinga
millionitemsrequiresonly20guesses. Continutingon,weneed21guessesfortwomillion,22forfour
million,23foreightmillion,and24guessestosearchamongsixteenmillionnames. Wecanfigureoutthe
nameofatotalstrangerinNewYorkCityusingonly24guesses! Bycomparison,alinearsearchwould
require(onaverage)6millionguesses.Binarysearchisaphenomenallygoodalgorithm!
IsaidearlierthatPythonusesalinearsearchalgorithmtoimplementitsbuilt-insearchingmethods.Ifa
binarysearchissomuchbetter,whydoesn
'
tPythonuseit?Thereasonisthatthebinarysearchislessgeneral;
inordertowork,thelistmustbeinorder.Ifyouwanttousebinarysearchonanunorderedlist,thefirstthing
youhavetodoisputitinorderorsortit. Thisisanotherwell-studiedproblemincomputerscience,and
onethatweshouldlookat. Beforeweturntosorting,however,weneedtogeneralizethealgorithmdesign
techniquethatweusedtodevelopthebinarysearch.
13.2 RecursiveProblem-Solving
Rememberthebasicideabehindthebinarysearchalgorithmwastosucessivelydividetheprobleminhalf.
Thisissometimesreferredtoasa“divideandconquer”approachtoalgorithmdesign,anditoftenleadsto
veryefficientalgorithms.
Oneinterestingaspectofdivideandconqueralorithmsisthattheoriginalproblemdividesintosubprob-
lemsthatarejustsmallerversionsoftheoriginal.ToseewhatImean,thinkaboutthebinarysearchagain.
Initially,therangetosearchistheentirelist.Ourfirststepistolookatthemiddleiteminthelist.Shouldthe
middleitemturnouttobethetarget,thenwearefinished.Ifitisnotthetarget,wecontinuebyperforming
binarysearchoneitherthetop-halforthebottomhalfofthelist.
Usingthisinsight,wemightexpressthebinarysearchalgorithminanotherway.
13.2. RECURSIVEPROBLEM-SOLVING
229
Algorithm: binarySearch h -- - search for x in range e nums[low] ] to nums[high]
mid = (low + high) ) / / 2
if low > high
x is not in n nums
elif x < nums[mid]
perform binary y search h for x in range nums[low] ] to o nums[mid-1]
else
perform binary y search h for x in range nums[mid+1] ] to o nums[high]
Ratherthanusingaloop,thisdefintionofthebinarysearchseemstorefertoitself. Whatisgoingonhere?
Canweactuallymakesenseofsuchathing?
13.2.1 RecursiveDefinitions
Adescriptionofsomethingthatreferstoitselfiscalledarecursivedefinition. Inourlastformulation,the
binarysearchalgorithmmakesuseofitsowndescription. A“call”tobinarysearch“recurs”insideofthe
definition—hence,thelabelrecursivedefinition.
Atfirstglance,youmightthinkrecursivedefinitionsarejustnonsense. Surelyyouhavehadateacher
whoinsistedthatyoucan
'
tuseawordinsideofitsowndefinition?That
'
scalledacirculardefinitionandis
usuallynotworthmuchcreditonanexam.
Inmathematics,however,certainrecursivedefinitionsareusedallthetime.Aslongasweexcercisesome
careintheformulationanduseofrecursivedefinitions,theycanbequitehandyandsurprisinglypowerful.
Let
'
slookatasimpleexampletogainsomeinsightandthenapplythoseideastobinarysearch.
Theclassicrecursiveexampleinmathematicsisthedefinitionoffactorial.BackinChapter3,wedefined
thefactorialofavaluelikethis:
n!
n
n
1
n
2
1
Forexample,wecancompute
5!
5
4
3
2
1
Recallthatweimplementedaprogramtocomputefactorialsusingasimpleloopthataccumulatesthefactorial
product.
Lookingatthecalculationof5!,youwillnoticesomethinginteresting.Ifweremovethe5fromthefront,
whatremainsisacalculationof4!. Ingeneral,n!
n
n
1
!. Infact,thisrelationgivesusanotherwayof
expressingwhatismeantbyfactorialingeneral.Hereisarecursivedefinition:
n!
1
ifn
0
n
n
1
! otherwise
Thisdefinitionsaysthatthefactorialof0is,bydefinition,1,whilethefactorialofanyothernumberisdefined
tobethatnumbertimesthefactorialofonelessthanthatnumber.
Eventhoughthisdefinitionisrecursive,itisnotcircular. Infact,itprovidesaverysimplemethodof
calculatingafactorial.Considerthevalueof4!.Bydefinitionwehave
4!
4
4
1
!
4
3!
Butwhatis3!?Tofindout,weapplythedefinitionagain.
4!
4
3!
4
3
3
1
!
4
3
2!
Now,ofcourse,wehavetoexpand2!,whichrequires1!,whichrequires0!. Since0!issimply1,that
'
sthe
endofit.
4!
4
3!
4
3
2!
4
3
2
1!
4
3
2
1
0!
4
3
2
1
1
24
Youcanseethattherecursivedefinitionisnotcircularbecauseeachapplicationcausesustorequestthe
factorialofasmallernumber.Eventuallywegetdownto0,whichdoesn
'
trequireanotherapplicationofthe
definition. Thisiscalledabasecasefortherecursion. . Whentherecursionbottomsout,wegetaclosed
expressionthatcanbedirectlycomputed.Allgoodrecursivedefinitionshavethesekeycharacteristics:
230
CHAPTER13. ALGORITHMANALYSISANDDESIGN
1. Thereareoneormorebasecasesforwhichnorecursionisrequired.
2. Whenthedefinitionisrecursivelyapplied,itisalwaysappliedtoasmallercase.
3. Allchainsofrecursioneventuallyendupatoneofthebasecases.
13.2.2 RecursiveFunctions
Youalreadyknowthatthefactorialcanbecomputedusingaloopwithanaccumulator.Thatimplementation
hasanaturalcorrespondencetotheoriginaldefinitionoffactorial. Canwealsoimplementaversionof
factorialthatfollowstherecursivedefinition?
Ifwewritefactorialasaseparatefunction,therecursivedefinitiontranslatesdirectlyintocode.
def fact(n):
if n == 0:
return 1L
else:
return n n * fact(n-1)
Doyouseehowthedefinitionthatreferstoitselfturnsintoafunctionthatcallsitself? Thefunctionfirst
checkstoseeifweareatathebasecasen == 0and,ifso,returns1(notetheuseofalongintconstant
sincefactorialsgrowrapidly).Ifwearenotyetatthebasecase,thefunctionreturnstheresultofmultiplying
nbythefactorialofn-1.Thelatteriscalculatedbyarecursivecalltofact(n-1).
Ithinkyouwillagreethatthisisareasonabletranslationoftherecursivedefinition.Thereallycoolpart
isthatitactuallyworks!Wecanusethisrecursivefunctiontocomputefactorialvalues.
>>> from recfact t import t fact
>>> fact(4)
24
>>> fact(10)
3628800
Somebeginningprogrammersaresurprisedbythisresult,butitfollowsnaturallyfromthesemanticsfor
functionsthatwediscussedwaybackinChapter6.Rememberthateachcalltoafunctionstartsthatfunction
anew.Thatmeansitgetsitsowncopyofanylocalvalues,includingthevaluesoftheparameters.Figure13.1
showsthesequenceofrecursivecallsthatcomputes2!. Noteespeciallyhoweachreturnvalueismultiplied
byavalueofnappropriateforeachfunctioninvocation. Thevaluesofnarestoredonthewaydownthe
chainandthenusedonthewaybackupasthefunctioncallsreturn.
fact(2)
n = 1
1
1
n = 0
2
n = 2
def fact(n):
if n == 0:
return 1
else:
return n * fact(n−1)
n:
def fact(n):
if n == 0:
return 1
else:
return n * fact(n−1)
n:
2
1
def fact(n):
if n == 0:
return 1
else:
return n * fact(n−1)
n:
0
Figure13.1:Recursivecomputationof2!
13.2.3 RecursiveSearch
Nowthatwehaveatechniqueforimplementingrecursivedefinitions,wearereadytogobackandlookagain
atbinarysearchasarecursiveprocess. Thebasicideawastolookatthemiddlevalueandthenrecursively
searcheitherthelowerhalfortheupperhalfofthearray.Thebasecasesfortherecursionaretheconditions
whenwecanstop,namelywhenthetargetvalueisfound,orwerunoutofplacestolook.Therecursivecalls
13.3. SORTINGALGORITHMS
231
willcutthesizeoftheprobleminhalfeachtime.Inordertodothis,weneedtospecifytherangeoflocations
inthelistthatarestill“inplay”foreachrecursivecall. Wecandothisbypassingthevaluesoflowand
highalongwiththelist.Eachinvocationwillsearchthelistbetweenthelowandhighindexes.
Hereisadirectimplementationoftherecursivealgorithmusingtheseideas:
def recBinSearch(x, , nums, , low, high):
if low > high:
# No place e left t to look, return -1
return -1
mid = (low w + + high) / 2
item = nums[mid]
if item == = x:
# Found it! ! Return n the index
return mid
elif x < item:
# Look in n lower r half
return recBinSearch(x, nums, low, mid-1)
else:
# Look in n upper r half
return recBinSearch(x, nums, mid+1, high)
Wecanthenimplementouroriginalsearchfunctionusingasuitablecalltotherecursivebinarysearch,telling
ittostartthesearchbetween0andlen(nums)-1
def search(x, , nums):
return recBinSearch(x, , nums, , 0, len(nums)-1)
Ofcourse,asinthecaseoffactorial,wealreadyimplementedthisalgorithmusingaloop,andthere
isnocompellingreasontousearecursiveimplementation. Infact,theloopingversionisprobablyabit
fasterbecausecallingfunctionsisgenerallyslowerthaniteratingaloop. Therecursiveversion,however,
makesthedivide-and-conquerstructureofbinarysearchmuchmoreobvious.Below,wewillseeexamples
whererecursivedivide-and-conquerapproachesprovideanaturalsolutiontosomeproblemswhereloopsare
awkward.
13.3 SortingAlgorithms
Thesortingproblemprovidesanicetestbedforthealgorithmdesigntechniqueswehavebeendiscussing.
Recall,thebasicsortingproblemistotakealistandrearrangeitsothatthevaluesareinincreasing(actually,
nondecreasing)order.
13.3.1 NaiveSorting:SelectionSort
Let
'
sstartwithasimple“bethecomputer”approachtosorting. Supposeyouhaveastackofindexcards,
eachwithanumberonit. Thestackhasbeenshuffled,andyouneedtoputthecardsbackinorder. How
wouldyouaccomplishthistask?
Thereareanynumberofgoodsystematicapproaches. Onesimplemethodistolookthroughthedeck
tofindthesmallestvalueandthenplacethatvalueatthefrontofthestack(orperhapsinaseparatestack).
Thenyoucouldgothroughandfindthesmallestoftheremainingcardsandputitnextinline,etc.Ofcourse,
thismeansthatyou
'
llalsoneedanalgorithmforfindingthesmallestremainingvalue.Youcanusethesame
approachweusedforfindingthemaxofalist(seeChapter6). Asyougothrough,youkeeptrackofthe
smallestvalueseensofar,updatingthatvaluewheneveryoufindasmallerone.
ThealgorithmIjustdescribediscalledselectionsort. Basically,thealgorithmconsistsofaloopand
eachtimethroughtheloop,weselectthesmallestoftheremainingelementsandmoveitintoitsproper
position. Applyingthisideatoalist,weproceedbyfindingthesmallestvalueinthelistandputtingitinto
the0thposition.Thenwefindthesmallestremainingvalue(frompositions1–(n-1))andputitinposition1.
Nextthesmallestvaluefrompositions2–(n-1)goesintoposition2,etc. Whenwegettotheendofthelist,
everythingwillbeinitsproperplace.
Thereisonesubtletyinimplementingthisalgorithm.Whenweplaceavalueintoitsproperposition,we
needtomakesurethatwedonotaccidentlylosethevaluethatwasoriginallystoredinthatposition. For
example,ifthesmallestitemisinposition10,movingitintoposition0involvesanassignment.
232
CHAPTER13. ALGORITHMANALYSISANDDESIGN
nums[0] = nums[10]
Butthiswipesoutthevaluecurrentlyinnums[0];itreallyneedstobemovedtoanotherlocationinthelist.
Asimplewaytosavethevalueistoswapitwiththeonethatwearemoving.Usingsimultaneousassignment,
thestatement
nums[0], nums[10] ] = = nums[10], nums[0]
placesthevaluefromposition10atthefrontofthelist,butpreservestheoriginalfirstvaluebystashingit
intolocation10.
Usingthisidea,itisasimplemattertowriteaselectionsortinPython. Iwilluseavariablecalled
bottomtokeeptrackofwhichpositioninthelistwearecurrentlyfilling,andthevariablempwillbeused
totrackthelocationofthesmallestremainingvalue.Thecommentsinthiscodeexplainthisimplementation
ofselectionsort:
def selSort(nums):
# sort nums s into o ascending order
n = len(nums)
# For each h position n in the list (except the e very y last)
for bottom m in n range(n-1):
# find the smallest item in nums[bottom]..nums[n-1]
mp = bottom
# initially y bottom m is smallest so far
for i in n range(bottom+1,n):
# look at t each h position
if nums[i] < nums[mp]:
# this one e is s smaller
mp = = i
#
remember its s index
# swap smallest item to the bottom
lst[bottom], lst[mp] ] = lst[mp], lst[bottom]
Onethingtonoticeaboutthisalgorithmistheaccumulatorforfindingtheminimumvalue. Ratherthan
actuallystoringtheminimumseensofar,mpjustremembersthepositionoftheminimum. Anewvalueis
testedbycomparingtheiteminpositionitotheiteminpositionmp.Youshouldalsonoticethatbottom
stopsatthesecondtolastiteminthelist. Oncealloftheitemsuptothelasthavebeenputintheproper
place,thelastitemhastobethelargest,sothereisnoneedtobotherlookingatit.
Theselectionsortalgorithmiseasytowriteandworkswellformoderate-sizedlists,butitisnotavery
efficientsortingalgorithm.We
'
llcomebackandanalyzeitafterwe
'
vedevelopedanotheralgorithm.
13.3.2 DivideandConquer:MergeSort
Asdiscussedabove,onetechniquethatoftenworksfordevelopingefficientalgorithmsisthedivide-and-
conquerapproach.SupposeafriendandIwereworkingtogethertryingtoputourdeckofcardsinorder.We
coulddividetheproblemupbysplittingthedeckofcardsinhalfwithoneofussortingeachofthehalves.
Thenwejustneedtofigureoutawayofcombiningthetwosortedstacks.
Theprocessofcombiningtwosortedlistsintoasinglesortedresultiscalledmerging.Ifyouthinkabout
it,mergingisprettysimple.Sinceourtwostacksaresorted,eachhasitssmallestvalueontop.Whicheverof
thetopvaluesisthesmallestwillbethefirstiteminthemergedlist.Oncethesmallervalueisremoved,we
canlookatthetopsofthestacksagain,andwhichevertopcardissmallerwillbethenextiteminthelist.We
justcontinuethisprocessofplacingthesmallerofthetwotopvaluesintothebiglistuntiloneofthestacks
runsout.Atthatpoint,wefinishoutthelistwiththecardsfromtheremainingstack.
HereisaPythonimplementationofthemergeprocess.Inthiscode,lst1andlst2arethesmallerlists
andlst3isthelargerlistwheretheresultsareplaced.Inorderforthemergingprocesstowork,thelength
oflst3mustbeequaltothesumofthelengthsoflst1andlst2.Youshouldbeabletofollowthiscode
bystudyingtheaccompanyingcomments:
Documents you may be interested
Documents you may be interested