chapter 4: loops - ucsbkoclab.cs.ucsb.edu/teaching/cs8/docx/ch04.pdf · common error: infinite...

Post on 07-Oct-2020

1 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Chapter4:Loops

ChapterGoals• Toimplementwhileandforloops

• Tohand-tracetheexecutionofaprogram

• Tobecomefamiliarwithcommonloopalgorithms

• Tounderstandnestedloops

• Toimplementprogramsthatreadandprocessdatasets

• Touseacomputerforsimulations

Inthischapter,youwilllearnaboutloopstatementsinPython,aswellastechniquesforwritingprogramsthatsimulateactivitiesinthereal

world.

24/6/16

Contents• Thewhile loop

• ProblemSolving:Hand-Tracing

• Application:ProcessingSentinels

• ProblemSolving:Storyboards

• CommonLoopAlgorithms

• Thefor loop

• Nestedloops

• ProcessingStrings

• Application:RandomNumbersandSimulation

• Graphics:DigitalImageProcessing

• ProblemSolving:SolveaSimplerProblemFirst

34/6/16

Thewhile Loop

4/6/16 4

Thewhile Loop• Examplesofloopapplications

• Calculatingcompoundinterest• Simulations,eventdrivenprograms• Drawingtiles…

• Compoundinterestalgorithm(Chapter1)

Steps

54/6/16

Planningthewhile Loopbalance=10.0target=100.0year=0rate=0.025whilebalance<TARGET:year=year+1interest=balance*RATE/100balance=balance+interest

AloopexecutesinstructionsrepeatedlywhileaconditionisTrue.

64/6/16

Syntax:while Statement

74/6/16

Count-ControlledLoops• Awhile loopthatiscontrolledbyacounter

counter = 1 # Initialize the counter

while counter <= 10 : # Check the counterprint(counter)counter = counter + 1 # Update the loop variable

84/6/16

Event-ControlledLoops• Awhile loopthatiscontrolledbyacounter

balance = INITIAL_BALANCE # Initialize the loop variable

while balance <= TARGET: # Check the loop variableyear – year + 1balance = balance * 2 # Update the loop variable

94/6/16

ExecutionoftheLoop

104/6/16

ExecutionoftheLoop(2)

114/6/16

Doubleinv.py

Declare andinitialize avariableoutsideofthe looptocountyear

Increment theyear variableeach timethrough

124/6/16

Investment Example• Openthefile:

• Doubleinv.py

• Runtheprogramwithseveraltestcases• Theprogramwillpromptyouforarate• Enteramixofvalidandinvalidrates

134/6/16

while LoopExamples

144/6/16

while LoopExamples (2)

154/6/16

CommonError: IncorrectTestCondition• TheloopbodywillonlyexecuteifthetestconditionisTrue.

• IfbalisinitializedaslessthantheTARGETandshouldgrowuntilitreachesTARGET• Whichversionwillexecute the loopbody?

while bal < TARGET :year = year + 1interest = bal * RATEbal = bal + interest

while bal >= TARGET :year = year + 1interest = bal * RATEbal = bal + interest

164/6/16

CommonError:InfiniteLoops• TheloopbodywillexecuteuntilthetestconditionbecomesFalse.

• Whatifyouforgettoupdatethetestvariable?• bal isthetestvariable (TARGET doesn’t change)• Youwill loopforever!(oruntilyoustoptheprogram)

while bal < TARGET :year = year + 1interest = bal * RATEbal = bal + interest

174/6/16

CommonError:Off-by-OneErrors• A‘counter’variableisoftenusedinthetestcondition

• Yourcountercanstartat0or1,butprogrammersoftenstartacounterat0

• IfIwanttopaintall5fingersononehand,whenIamdone?• Ifyoustartat0,use“<“ Ifyoustartat1,use“<=“• 0,1,2,3,4 1,2,3,4,5

finger = 0FINGERS = 5while finger < FINGERS :

# paint fingerfinger = finger + 1

finger = 1FINGERS = 5while finger <= FINGERS :

# paint fingerfinger = finger + 1

184/6/16

HandTracingLoops

4/6/16 19

Hand-Tracing Loops• Example:Calculatethesumofdigits(1+7+2+9)

• Makecolumnsforkeyvariables(n,total,digit)• Examinethecodeandnumberthesteps• Setvariablestostatebeforeloopbegins

204/6/16

TracingSumofDigits

• Startexecutingloopbodystatementschangingvariablevaluesonanewline• Crossoutvaluesinpreviousline

214/6/16

TracingSumofDigits

• Continueexecutingloopstatementschangingvariables• 1729/10leaves172(noremainder)

224/6/16

TracingSumofDigits• Testcondition.IfTrue,executeloopagain

• Variablenis172,Is172>0?,True!

• Makeanewlineforthesecondtimethroughandupdatevariables

234/6/16

TracingSumofDigits• Thirdtimethrough

• Variablenis17whichisstillgreaterthan0

• Executeloopstatementsandupdatevariables

244/6/16

TracingSumofDigits• Fourthloopiteration:

• Variablenis1atstartofloop.1>0?True• Executesloopandchangesvariablento0(1/10=0)

254/6/16

TracingSumofDigits• Becausenis0,theexpression(n>0)isFalse

• Loopbodyisnotexecuted• Jumpstonextstatementaftertheloopbody

• Finallyprintsthesum!

264/6/16

Summaryofthewhile Loop• while loopsareverycommon

• Initializevariablesbeforeyoutest• TheconditionistestedBEFOREtheloopbody

• Thisiscalledpre-test• Theconditionoftenusesacountervariable

• Somethinginsidetheloopshouldchangeoneofthevariablesusedinthetest

• Watchoutforinfiniteloops!

274/6/16

SentinelValues

4/6/16 28

ProcessingSentinelValues• Sentinelvaluesareoftenused:

• Whenyoudon’tknowhowmanyitems are inalist,usea‘special’characterorvaluetosignalthe “last” item

• Fornumeric inputofpositive numbers, it iscommon tousethevalue-1

Asentinelvaluedenotestheendofadataset,butitisnotpartofthedata.

salary = 0.0while salary >= 0 :

salary = float(input())if salary >= 0.0 :

total = total + salarycount = count + 1

294/6/16

AveragingaSetofValues• Declareandinitializea‘total’variableto0

• Declareandinitializea‘count’variableto0

• Declareandinitializea‘salary’variableto0

• Promptuserwithinstructions

• Loopuntilsentinelvalueisentered• Saveenteredvaluetoinputvariable(‘salary’)• Ifsalaryisnot-1orless(sentinelvalue)

• Addsalaryvariabletototalvariable• Add1tocountvariable

• Makesureyouhaveatleastoneentrybeforeyoudivide!• Dividetotalbycountandoutput.• Done!

304/6/16

Sentinel.py (1)

Outside the while loop: declare and initialize variables to use

Input new salary and compare to sentinel

Update running total and count (to calculate the average later)

Since salary is initialized to 0, the while loop statements will execute at least once

314/6/16

Sentinel.py (2)

Prevent divide by 0

Calculate and output the average salary using the total and countvariables

324/6/16

SentinelExample• Openthefile:

• Sentinal.py

• NoticetheuseoftheIF() testinsidethewhile loop• TheIF()checkstomakesurewearenotprocessingthesentinelvalue

334/6/16

PrimingRead• Someprogrammersdon’tlikethe“trick”ofinitializingtheinputvariablewithavalueotherthanasentinel.

# Set salary to a value to ensure that the loop # executes at least once.salary = 0.0while salary >= 0 :

salary = float(input("Enter a salary or -1 to finish: "))while salary >= 0 :

344/6/16

• Analternativeistochangethevariablewithareadbeforetheloop.

ModificationRead• Theinputoperationatthebottomoftheloopisusedtoobtainthenextinput.

# Priming readsalary = float(input("Enter a salary or -1 to finish: "))while salary >= 0.0 :

total = total + salarycount = count + 1# Modification readsalary = float(input("Enter a salary or -1 to finish: "))

354/6/16

BooleanVariablesandSentinels• Abooleanvariablecanbeusedtocontrolaloop

• Sometimescalleda‘flag’variable

done = Falsewhile not done :

value = float(input("Enter a salary or -1 to finish: "))if value < 0.0:

done = Trueelse :

# Process value

Initialize done so that the loop will execute

Set done ‘flag’ to True if sentinel value is found

364/6/16

Storyboards

4/6/16 37

Storyboards• Oneusefulproblemsolvingtechniqueistheuseofstoryboardstomodeluserinteraction.Itcanhelpanswer:• Whatinformationdoestheuserprovide,andinwhichorder?• Whatinformationwillyourprogramdisplay,andinwhichformat?• Whatshouldhappenwhenthereisanerror?• Whendoestheprogramquit?

• Astoryboardconsistsofannotatedsketchesforeachstepinanactionsequence.

384/6/16

StoryboardExample• Goal:Convertingasequenceofvalues

• Willrequirealoopandsomevariables• Handleoneconversioneachtimethroughtheloop

394/6/16

WhatCanGoWrong?Unknownunittypes

• Whatistheusermisspellscentimetersandinches?• Whatotherconversionsareavailable?• Solution:

• Showalistoftheacceptableunittypes

404/6/16

WhatElseCanGoWrong?• Howdoestheuserquittheprogram?

• Storyboardshelpyouplanaprogram• Knowingtheflowhelps youstructure yourcode

414/6/16

CommonLoopAlgorithms

4/6/16 42

CommonLoopAlgorithms1. SumandAverageValue

2. CountingMatches

3. PromptinguntilaMatchIsFound

4. MaximumandMinimum

5. ComparingAdjacentValues

434/6/16

AverageExampletotal = 0.0count = 0inputStr = input("Enter value: ")while inputStr != "" :

value = float(inputStr)total = total + valuecount = count + 1inputStr = input("Enter value: ")

if count > 0 : average = total / count

else :average = 0.0

AverageofValues• Firsttotalthevalues• Initializecount to0

• Incrementperinput• Checkforcount 0

• Beforedivide!

444/6/16

SumExample• SumofValues

• Initializetotalto0• Usewhileloopwithsentinel

total = 0.0inputStr = input("Enter value: ")while inputStr != "" :

value = float(inputStr)total = total + valueinputStr = input("Enter value: ")

454/6/16

CountingMatches(e.g.,NegativeNumbers)

negatives = 0inputStr = input("Enter value: ")while inputStr != "“ :

value = int(inputStr)if value < 0 :

negatives = negatives + 1inputStr = input("Enter value: ")

print("There were", negatives, "negative values.")

• CountingMatches• Initializenegatives to0• Useawhile loop• Addtonegatives permatch

464/6/16

PromptUntilaMatchisFound• InitializebooleanflagtoFalse

• Testsentinelinwhileloop• Getinput,andcomparetorange

• Ifinputisinrange,changeflagtoTrue• Loopwillstopexecuting

valid = Falsewhile not valid :

value = int(input("Please enter a positive value < 100: "))if value > 0 and value < 100 :

valid = Trueelse :

print("Invalid input.")

47

Thisisanexcellentwaytovalidateuseprovidedinputs

4/6/16

Maximum• Getfirstinputvalue

• Bydefinition,thisisthelargestthatyouhaveseensofar

• Loopwhileyouhaveavalidnumber(non-sentinel)• Getanotherinputvalue• Comparenewinputtolargest(orsmallest)• Updatelargestifnecessary

largest = int(input("Enter a value: "))inputStr = input("Enter a value: ")while inputStr != "“ :

value = int(inputStr)if value > largest :

largest = valueinputStr = input("Enter a value: ")

484/6/16

Minimum• Getfirstinputvalue

• Thisisthesmallestthatyouhaveseensofar!

• Loopwhileyouhaveavalidnumber(non-sentinel)• Getanotherinputvalue• Comparenewinputtolargest(orsmallest)• Updatesmallestifnecessary

smallest = int(input("Enter a value: "))inputStr = input("Enter a value: ")while inputStr != "“ :

value = int(inputStr)if value < smallest :

smallest = valueinputStr = input("Enter a value: ")

494/6/16

ComparingAdjacentValues• Getfirstinputvalue

• Usewhile todetermineiftherearemoretocheck• Copyinputtopreviousvariable• Getnextvalueintoinputvariable• Compareinputtoprevious,andoutputifsame

value = int(input("Enter a value: "))inputStr = input("Enter a value: ")while inputStr != "“ :

previous = valuevalue = int(inputStr)if value == previous :

print("Duplicate input")inputStr = input("Enter a value: ")

504/6/16

GradesExample• Openthefile:

• Grades.py

• Lookcarefullyatthesourcecode.

• Themaximumpossiblescoreisreadasuserinput• Thereisalooptovalidatetheinput

• Thepassinggradeiscomputedas60%oftheavailablepoints

514/6/16

Thefor Loop

4/6/16 52

Thefor Loop• Usesofafor loop:

• Thefor loopcanbeusedtoiterateoverthecontentsofanycontainer.

• Acontainer isisanobject(Likeastring)thatcontainsorstoresacollectionofelements

• Astring isacontainerthatstoresthecollectionofcharactersinthestring

534/6/16

AnExampleofafor Loop

stateName = "Virginia"i = 0while i < len(stateName) :

letter = stateName[i]print(letter)i = i + 1

whileversion

stateName = "Virginia"for letter in stateName :

print(letter) forversion

• Noteanimportantdifferencebetweenthewhileloopandtheforloop.• Inthewhileloop,theindexvariablei isassigned0,1,andsoon.• Intheforloop,theelementvariableisassignedstateName[0],stateName[1],andsoon.

544/6/16

TheforLoop(2)• Usesofaforloop:

• Aforloopcanalsobeusedasacount-controlledloopthatiteratesoverarangeofintegervalues.

i = 1while i < 10 :

print(i)i = i + 1

for i in range(1, 10) : print(i)

while version

for version

554/6/16

Syntaxofafor Statement (Container)• Usingaforlooptoiterateoverthecontentsofacontainer,anelementatatime.

564/6/16

Syntaxofafor Statement (Range)• Youcanuseaforloopasacount-controlledlooptoiterateoverarangeofintegervalues

• Weusetherangefunctionforgeneratingasequenceofintegersthatlessthantheargumentthatcanbeusedwiththeforloop

574/6/16

Planningafor Loop• Printthebalanceattheendofeachyearforanumberofyears

584/6/16

GoodExamplesoffor Loops• Keeptheloopssimple!

594/6/16

Investment Example

604/6/16

ProgrammingTip• Findingthecorrectlowerandupperboundsforaloopcanbeconfusing.• Shouldyoustartat0orat1?• Shouldyouuse<=bor<basaterminationcondition?

• Countingiseasierforloopswithasymmetricbounds.• Thefollowingloopsareexecutedb- atimes.

int i = awhile i < b :

. . .i = i + 1

for i in range(a, b) :. . .

614/6/16

ProgrammingTip• Theloopwithsymmetricbounds(“<=”,isexecutedb- a+1times.

• That“+1”isthesourceofmanyprogrammingerrors.

i = awhile i <= b :

. . .i = i + 1

# For this version of the loop the ‘+1’ is very noticeable!for year in range(1, numYears + 1) :

624/6/16

Summaryofthefor Loop• for loopsareverypowerful

• Thefor loopcanbeusedtoiterateoverthecontentsofanycontainer,whichisanobjectthatcontainsorstoresacollectionofelements• astring isacontainer thatstoresthecollection ofcharacters inthestring.

• Afor loopcanalsobeusedasacount-controlledloopthatiteratesoverarangeofintegervalues.

634/6/16

StepstoWriting aLoop• Planning:

• Decidewhatworktodoinsidetheloop• Specifytheloopcondition• Determinelooptype• Setupvariablesbeforethefirstloop• Processresultswhentheloopisfinished• Tracetheloopwithtypicalexamples

• Coding:• ImplementtheloopinPython

644/6/16

ASpecialFormoftheprint Function• Pythonprovidesaspecialformoftheprintfunctionthatdoesnotstartanewlineaftertheargumentsaredisplayed

• Thisisusedwhenwewanttoprintitemsonthesamelineusingmultipleprintstatements

• Forexamplethetwostatements:

print(“00”, end=””)print(3 + 4)

• Producetheoutput:

007

• Includingend=“” asthelastargumenttotheprintfunctionprintsanemptystringafterthearguments,insteadonanewline

• Theoutputofthenextprint functionstartsonthesameline

4/6/16 65

NestedLoops

4/6/16 66

LoopsInsideofLoops• InChapterThreewelearnedhowtonestif statementstoallowustomakecomplexdecisions• Rememberthattonesttheif statementsweneedtoindentthecodeblock

• Complexproblemssometimesrequireanestedloop,oneloopnestedinsideanotherloop• Thenestedloopwillbeindentedinsidethecodeblockofthefirstloop

• Agoodexampleofusingnestedloopsiswhenyouareprocessingcellsinatable• Theouterloopiteratesoveralloftherowsinthetable• Theinnerloopprocessesthecolumnsinthecurrentrow

4/6/16 67

OurExampleProblemStatement• PrintaTableHeaderthatcontainsx1,x2,x3,andx4

• PrintaTablewithfourcolumnsandtenrowsthatcontainthepowersofx1,x2,x3,andx4 forx=1to10

4/6/16 68

ApplyingNestedLoops• Howwouldyouprintatablewithrowsandcolumns?

• Printtopline(header)• Useaforloop

• Printtablebody…• Howmanyrowsareinthetable?• Howmanycolumnsinthetable?

• Loopperrow• Looppercolumn

• Inourexamplethereare:• Fourcolumnsinthetable• Tenrowsinthetable

4/6/16 69

PseudocodetoPrinttheTablePrintthetableheader

for x from 1 to 10print a new table rowprint a new line

• Howdoweprintatablerow?

For n from 1 to 4print xn

• Wehavetoplacethisloopinsidetheprecedingloop• Theinnerloopis“nested”insidetheouterloop

4/6/16 70

PseudocodetoPrinttheTablePrintthetableheader:

for x from 1 to 10for n from 1 to 4print Xn

print a new line

4/6/16 71

n è

InnerLoop

FlowchartofaNestedLoopx=1

x<=10?

n=1

n<=4?

Printxn

n=n+1

Printnewline

x=x+1

True

False True

Done

False

4/6/16 72

Powertable.py

4/6/16 73

Bodyofouterloop,x=1è 10

Bodyofinnerloop,n=1è 4

The end=“” suppresses the new line, so the numbers are all printed on the same line

TheResults

4/6/16 74

FirstExercise• Opentheprogram:

• powertable.py

• Runtheprogramandreviewtheresults

• Makethefollowingchanges:• ChangethevalueofNMAXto6andruntheprogram• Whatchangesinthetable?• ChangethevalueofNMAXbackto4• ChangethevalueofXMAXto4• Whatchangesinthetable?

4/6/16 75

NestedLoopExamples

4/6/16 76

HandTracingtheLoop

• i willhavethevalues:• 0,1,2,3– Sowewillhavefourlinesofstars

• j willhavethevalues• 0- Sowewillhaveonestar• 0,1- Sowewillhavetwostars• 0,1,2- Sowewillhavethreestars• 0,1,2,3- Sowewillhavefourstars

4/6/16 77

NestedLoopExamples (2)

4/6/16 78

SecondProblemStatement• Printthefollowingpatternofbrackets:[][][][][][][][][][][][]

• Thepatternconsistsof:• Threerows• Eachrowhasfourpairsofbrackets

• Whatdoweknow?• Weneedtwonestedloops

• Thefirstloop(theouterloop)willprinteachofthethreerows• Thesecondloop(theinnerloop)willprintthefourpairsofbrackets

4/6/16 79

PseudocodeCode,ResultsFor i = 1 to 3For j = 1 to 4Print “[]”

Print a new line

4/6/16 80

ExamAveragesProblemStatement• Itiscommontorepeatedlyreadandprocessmultiplegroupsofvalues:

• Writeaprogramthatcancomputetheaverageexamgradeformultiplestudents.

• Eachstudenthasthesamenumberofexamgrades• Prompttheuserforthenumberofexams• Whenyoufinishastudentprompttheusertoseeiftherearemorestudentstoprocess

• Whatdoweknow?

• Whatdoweneedtocompute?

• Whatisouralgorithm/approach?

4/6/16 81

StepOne:UnderstandtheProblem• Tocomputetheaveragegradeforastudent,wemustreadandtallyallofthegradesforthatstudent• Wecanusealooptodothis.(wehaveworkingcodetodothisportion)

• Weneedtocomputegradesformultiplestudents• ThatimpliesasetofnestedLoops

• Theouterloopprocesseseachstudent• Theinnerloopprocessthestudent’sgrades

4/6/16 82

StepTwo• Computethegradeforonestudent

• Setupthevariablesandloop

• Weknowhowmanygradestoprocess,sowecanuseacount-controlledloop

total score = 0For i in range (1, number of exams + 1) :Read the next exam scoreAdd the exam score to the total score

Compute the exam averagePrint the exam average

4/6/16 83

StepThree• Repeattheprocessforeachstudent

• Sincewedon’tknowhowmanystudentsthereare,wewilluseawhileloopwithasentinelvalue• Forsimplicitywewilluse“Y”asthesentinelvalue

4/6/16 84

StepFour:Translate toPython

4/6/16 85

ExamAverages Example• Openthefile:

• examaverages.py

• Noticethatthesecondloop(thefor loop)isnestedinsidethewhile loop

• Youshouldseealine(theindentguide)connectingthefor looponline17downtothestatementonline21• Thelineisshowingyouthestatementsthatareincludedinthefor loop

• Ifyoudon’tseetheindentguide:• Clickontheedittab• Select“Preferences…”• UnderEditor,selectIndention• Clickthe“ShowIndentGuides”box• ClicktheApplybutton• ClicktheOkayButton

4/6/16 86

TurningtheIndentGuidesOn

4/6/16 87

ProcessingStrings• Acommonuseofloopsistoprocessorevaluatestrings.

• Forexample,youmayneedtocountthenumberofoccurrencesofoneormorecharactersinastringorverifythatthecontentsofastringmeetcertaincriteria.

4/6/16 88

ProcessingStrings

4/6/16 89

StringProcessingExamples• CountingMatches

• FindingAllMatches

• FindingtheFirstorLastMatch

• ValidatingaString

• BuildingaNewString

4/6/16 90

CountingMatches• Supposeyouneedtocountthenumberofuppercaseletterscontainedinastring.

• Wecanuseaforlooptocheckeachcharacterinthestringtoseeifitisuppercase

• Theloopbelowsetsthevariablecharequaltoeachsuccessivecharacterinthestring

• Eachpassthroughtheloopteststhenextcharacterinthestringtoseeifitisuppercase

uppercase = 0for char in string :

if char.isupper() :uppercase = uppercase + 1

4/6/16 91

CountingVowels• Supposeyouneedtocountthevowelswithinastring

• Wecanuseaforlooptocheckeachcharacterinthestringtoseeifitisinthestringofvowels“aeiuo”

• Theloopbelowsetsthevariablecharequaltoeachsuccessivecharacterinthestring

• Eachpassthroughtheloopteststhelowercaseofthenextcharacterinthestringtoseeifitisinthestring“aeiou”

vowels = 0for char in word :

if char.lower() in "aeiou" :vowels = vowels + 1

4/6/16 92

FindingAllMatchesExample• Whenyouneedtoexamineeverycharacterinastring,independentofitspositionwecanuseaforstatementtoexamineeachcharacter

• Ifweneedtoprintthepositionofeachuppercaseletterinasentencewecantesteachcharacterinthestringandprintthepositionofalluppercasecharacters

• Wesettherangetobethelengthofthestring• Wetesteachcharacter• Ifit isuppercase weprintI,its position inthestring

sentence = input("Enter a sentence: ")for i in range(len(sentence)) :

if sentence[i].isupper() :print(i)

4/6/16 93

FindingtheFirstMatch• Thisexamplefindsthepositionofthefirstdigitinastring.

found = Falseposition = 0while not found and position < len(string) :

if string[position].isdigit() :found = True

else :position = position + 1

if found :print("First digit occurs at position", position)

else :print("The string does not contain a digit.")

4/6/16 94

FindingtheLastMatch• Hereisaloopthatfindsthepositionofthelastdigitinthestring.

• Thisapproachusesawhilelooptostartatthelastcharacterinastringandtesteachvaluemovingfromtheendofthestringtothestartofthestring• Position issettothe length ofthestring - 1• Ifthecharacter isnotadigit,wedecrease position by1• Untilwefindadigit,orprocessall thecharacters

found = Falseposition = len(string) - 1while not found and position >= 0 :

if string[position].isdigit() :found = True

else :position = position - 1

4/6/16 95

ValidatingaString• IntheUnitedStates,telephonenumbersconsistofthreeparts––areacodeexchange,andlinenumber––whicharecommonlyspecifiedintheform(###)###-####.

4/6/16 96

ValidatingaString (code)• Wecanexamineastringtoensurethatitcontainsacorrectlyformattedphonenumber.(e.g.,(703)321-6753)

• Thelooptesteachcharactertoseeititiscorrectforitsposition,oranumber

valid = len(string) == 13position = 0while valid and position < len(string) :

valid = ((position == 0 and string[position] != "(")or (position == 4 and string[position] != ")")or (position == 8 and string[position] != "-")or (position != 0 and position != 4 and position != 8

and string[position].isdigit())) :position = position + 1

4/6/16 97

Building aNewString• Oneoftheminorannoyancesofonlineshoppingisthatmanywebsitesrequireyoutoenteracreditcardwithoutspacesordashes,whichmakesdouble-checkingthenumberrathertedious.

• Howhardcanitbetoremovedashesorspacesfromastring?

4/6/16 98

Building aNewString (code)• Thecontentsofastringcannotbechanged.

• Butnothingpreventsusfrombuildinganewstring.

• Hereisaloopthatbuildsanewstringcontainingacreditcardnumberwithspacesanddashesremoved:• Wereadthecreditcardnumber• Weinitializeanewstringtotheemptystring• Wetesteachcharacterintheuserinput

• Ifthecharacterisnotaspaceordashweappendittothenewstring

userInput = input("Enter a credit card number: ")creditCardNumber = ""for char in userInput :

if char != " " and char != "-" :creditCardNumber = creditCardNumber + char

4/6/16 99

Application: RandomNumbersandSimulations

4/6/16 100

RandomNumbers/Simulations• Gamesoftenuserandomnumberstomakethingsinteresting

• RollingDice• Spinningawheel• Pickacard

• Asimulationusuallyinvolvesloopingthroughasequenceofevents• Days• Events

4/6/16 101

GeneratingRandomNumbers• ThePythonlibraryhasarandomnumbergeneratorthatproducesnumbersthatappear toberandom• Thenumbersarenotcompletelyrandom.Thenumbersaredrawnfromasequenceofnumbersthatdoesnotrepeatforalongtime

• random()returnsanumberthatis>=0and<1

4/6/16 102

SimulatingDieTosses• Goal:

• Togeneratearandomintegerinagivenrangeweusetherandint()function

• Randinthastwoparameters,therange(inclusive)ofnumbersgenerated

4/6/16 103

TheMonteCarloMethod• Usedtofindapproximatesolutionstoproblemsthatcannotbepreciselysolved

• Example:ApproximatePIusingtherelativeareasofacircleinsideasquare• Usessimplearithmetic• Hitsareinsidecircle• Triesaretotalnumberoftries• Ratiois4xHits/Tries

4/6/16 104

MonteCarloExample

4/6/16 105

ImageProcessing

4/6/16 106

Manipulating Images• Digitalimageprocessingistheuseofalgorithmstomanipulatedigitalimages

• Itisusedin:• Digital photography• Datacompression• Computer graphics• Computer vision• Robotics

• We’lllearnhowtomanipulateimageswiththeezgraphics package

4/6/16 107

Representing Images• Adigitalimageiscomposedofpixelsarrangedinagridofrowsandcolumns• Computer images appear “smooth” because verysmallpoints onthescreen(veryclose together) areused toreproducethe individual pixels

• Pixelsstoredatarepresentingacolorfromthevisualspectrum• Thediscrete RGBcolormodel isthemostusedmodel• Thethree individual colorsarespecified bytheamount ofred,green,andblue light needed toproduceagivencolor

• Thevaluesaregivenas integers between 0(nolightpresent) and255(maximum light present)

4/6/16 108

FilteringanImage• Filteringanimagemodifiesthecolorcomponentvaluesofeachpixelinsomeway

4/6/16 109

ProcessinganImage• Westartbyloadingtheimageintoourprogram

• Inezgraphicsanimage isstored inaninstance oftheGraphicsImage classfilename = "queen-mary.gif"image = GraphicsImage(filename)

• WedrawtheimageonthecanvasofaGraphicsWindowwin = GraphicsWindow()canvas = win.canvas()canvas.drawImage(image)win.wait()

4/6/16 110

FilteringanImage• Tofilteranimage,youmustgetthered,green,andbluecomponentvaluesforeachpixel.• Thepixels areorganized intoatwo-dimensional gridofsizewidth× height:• Therowsandcolumns arenumbered sequentially startingat0,withpixel(0,0)intheupper-left corner.

• Therownumbers rangefrom0toheight– 1;thecolumnnumbers from0towidth– 1.

4/6/16 111

AccessingtheComponentValuesofaPixel• WeusethegetRed,getGreen andgetBluemethodsred = image.getRed(0, 4)green = image.getGreen(0, 4)blue = image.getBlue(0, 4)

• Tocreatethenegativeofanimage:

newRed = 255 - rednewGreen = 255 - greennewBlue = 255 – blue

• Andthenupdatethepixel

image.setPixel(0,4,newRed,newGreen,newBlue)

4/6/16 112

ThePseudocodewidth = image.width()height = image.height()for row in range(height) :

for col in range(width) :Get the current pixel color.Filter the pixel.Set the pixel to the new color.

image.save("negative" + filename)

4/6/16 113

GraphicsImage Methods

4/6/16 114

ProblemSolving:SolveaSimplerProblemFirst

4/6/16 115

SimplifyaComplexProblem• Aswelearnmoreaboutprogramming,thecomplexityofthetaskswearesolvingincreases

• Whenwearefacedwithacomplextaskweshouldapplyacriticalskill:• Simplifying theproblem andsolving thesimpler problem first

• Oursimplification(AKAproblemdecomposition)skillsimprovewithpractice

4/6/16 116

ASampleProblem• Ourassignmentistoarrangepictures,liningthemupalongthetopedges,separatingthemwithsmallgaps,andstartinganewrowwheneveryourunoutofroominthecurrentrow.• Thissounds simple, right?

4/6/16 117

ASimplePlan• Let’sdevelopaplanthatsolvesasetofsimpler(increasingincomplexity)problems

4/6/16 118

Increase theComplexity

4/6/16 119

ImplementingOurPlan1. Specifythecanvascoordinateswheretheupperleftcornerofthefirst

imageshouldbeplaced

2. Thenplacethenextpictureafterthefirstafterthefirst• Itneedstobedrawnsothatitsleft-mostedgeispositionedattheright-mostx-coordinateoftheprecedingpicture

• Thiscanbedeterminedbyobtainingthewidthofthefirstpictureandusingthatvalueasthex-coordinateforthesecondpicture

3. Separatethetwopictureswithagap

4. Todrawthethirdpicture,it’snotsufficienttoknowthewidthoftheprecedingpicture.• Wealsoneedtoknowthex-coordinatewhereitwasdrawnsowecanaddthatvaluetothewidthoftheprecedingimage,plusthegapbetweentheimages

4/6/16 120

ImplementingourPlan5. Nowlet’sputallofthepicturesinarow

• Loadthepicturesinaloop,andthenputeachpicturetotherightoftheonethatprecededit.

• Ineachiteration,youneedtotracktwopictures:theonethatisbeingloaded,andtheonethatprecededit

6. Wedon’twanttohaveallpicturesinasinglerow• TherightmarginofapictureshouldnotextendpastMAX_WIDTH• Iftheimagedoesn’tfitweneedtoputitonthenextrow,belowallthepicturesinthecurrentrow

• We’llsetavariablemaxY tothemaximumy-coordinateofallplacedpictures,updatingitwheneveranewpictureisplaced

4/6/16 121

Summary

4/6/16 122

Summary: TwoTypesofLoops• while Loops

• for Loops

• while loopsareverycommonlyused(generalpurpose)

• Usesofthefor loop:• Thefor loopcanbeusedtoiterateoverthecontentsofanycontainer.

• Afor loopcanalsobeusedasacount-controlledloopthatiteratesoverarangeofintegervalues.

1234/6/16

Summary• Eachlooprequiresthefollowingsteps:

• Initialization(setupvariablestostartlooping)• Condition(testifweshouldexecuteloopbody)• Update(changesomethingeachtimethrough)

• AloopexecutesinstructionsrepeatedlywhileaconditionisTrue.

• Anoff-by-oneerrorisacommonerrorwhenprogrammingloops.• Thinkthroughsimpletestcasestoavoidthistypeoferror.

1244/6/16

Summary• Asentinelvaluedenotestheendofadataset,butitisnotpartofthedata.

• Youcanuseabooleanvariabletocontrolaloop.• SetthevariabletoTrue beforeenteringtheloop• SetittoFalse toleavetheloop.

• Loopscanbeusedinconjunctionwithmanystringprocessingtasks

1254/6/16

Summary• Inasimulation,youusethecomputertosimulateanactivity.

• Youcanintroduce randomness bycallingtherandomnumbergenerator.

4/6/16 126

top related