Python Programming: An Introduction to Computer Science

(Nora) #1
136 CHAPTER8. CONTROLSTRUCTURES,PART 2


  1. A postive wholenumbern 2 is primeif nonumberbetween2 and n(inclusive)evenlydividesn.
    Writea programthatacceptsa valueofnasinputanddeterminesif thevalueis prime. Ifnisnot
    prime,yourprogramshouldquitassoonasit findsa valuethatevenlydividesn.

  2. Modifythepreviousprogramtofindeveryprimenumberlessthanorequalton.

  3. Thegreatestcommondivisor(GCD)oftwo valuescanbecomputedusingEuclid’s algorithm.Starting
    withthevaluesmandn, werepeatedlyapplytheformula:n, m = m, n%muntilmis 0.Atthat
    point,nis theGCDoftheoriginalmandn. Writea programthatfindstheGCDoftwo numbersusing
    thisalgorithm.

  4. Writea programthatcomputesthefuelefficiency ofa multi-leg journey. Theprogramwillfirstprompt
    forthestartingodometerreadingandthengetinformationabouta seriesoflegs. Foreachleg,the
    userentersthecurrentodometerreadingandtheamountofgasused(separatedbya space).Theuser
    signalstheendofthetripwitha blankline.Theprogramshouldprintoutthemilespergallonachieved
    oneachleg andthetotalMPGforthetrip.

  5. Modifythepreviousprogramtogetitsinputfroma file.

  6. Heatingandcoolingdegree-daysaremeasuresusedbyutilitycompaniestoestimateenergyrequire-
    ments.If theaveragetemperaturefora dayis below 60,thenthenumberofdegreesbelow 60is added
    totheheatingdegree-days.If thetemperatureis above 80,theamountover 80 is addedtothecooling
    degree-days.Writea programthatacceptsa sequenceofaveragedailytempsandcomputestherunning
    totalofcoolingandheatingdegree-days.Theprogramshouldprintthesetwo totalsafterallthedata
    hasbeenprocessed.

  7. Modifythepreviousprogramtogetitsinputfroma file.

  8. Writea programthatgraphicallyplotsa regressionline,thatis,thelinewiththebestfitthrougha
    collectionofpoints. Firstasktheusertospecifythedatapointsbyclickingonthemina graphics
    window. To findtheendofinput,placea smallrectanglelabelled“Done”inthelowerleftcornerof
    thewindow;theprogramwillstopgatheringpointswhentheuserclicksinsidethatrectangle.
    Theregressionlineis thelinewiththefollowingequation:


y ̄y m


x ̄x

where
m
∑xiyi n ̄x ̄y
∑x^2 i n ̄x^2
̄xis themeanofthex-valuesand ̄yis themeanofthey-values.
Astheuserclicksonpoints,theprogramshoulddraw theminthegraphicswindow andkeeptrackof
thecountofinputvaluesandtherunningsumofx,y,x^2 andxyvalues.Whentheuserclicksinsidethe
“Done”rectangle,theprogramthencomputesvalueofy(usingtheequationsabove)correpondingto
thexvaluesattheleftandrightedgesofthewindow tocomputetheendpointsoftheregressionline
spanningthewindow. Afterthelineis drawn,theprogramwillpauseforanothermouseclickbefore
closingthewindow andquitting.
Free download pdf