Python Programming: An Introduction to Computer Science

(Nora) #1
3.7.EXERCISES 37


  1. TheGregorianEpactis thenumberofdaysbetweenJan.1standtheprevious1stquartermoonphase.
    Thisvalueis usedtofigureoutthedateofEaster. It is calculatedbytheseformulas(usingintarith-
    metic):C year



100 epact


8 


C


4  C


8 C 13 


25  11


year%19%30Writea program
thatpromptstheuserfora 4-digityearandthenoutputsthevalueoftheepact.


  1. Writea programtocalculatetheareaofa trianglegiventhelengthofitsthreesidesa,b,andc.
    s a


 bc
2 A  s


s a


s b


s c


  1. Writea programtodeterminethelengthofa ladderrequiredtoreacha givenheightwhenleaned
    againsta house.Theheightandangleoftheladderaregivenasinputs.len sinheighanglte

  2. Writea programtofindthesumofthefirstn naturalnumbers,wherethevalueofn is providedbythe
    user.

  3. Writea programtofindthesumofthesquaresforthefirstn naturalnumbers.

  4. Writea programtosuma seriesofnumbersenteredbytheuser. Theprogramshouldfirstpromptthe
    userforhowmany numbersaretobesummed.It shouldtheninputeachofthenumbersandprinta
    totalsum.

  5. Writea programthatfindstheaverageofa seriesofnumbersenteredbytheuser. Asintheprevious
    problem,theprogramwillfirstasktheuserhowmany numbersthereare.Note:theaverageshould
    alwaysbea float,evenif theuserinputsareallints.

  6. Writea programthatapproximatesthevalueofπbysummingthetermsofthisseries: 4



1  4


3 
4


5  4


7  4


9  4


11  Theprogramshouldprompttheuserforn,thenumberoftermstosum
andthenoutputthesumofthefirstn termsofthisseries.


  1. AFibonaccisequenceisa sequenceofnumberswhereeachsuccessive numberisthesumofthe
    previoustwo. TheclassicFibonaccisequencebegins:1,1,2,3,5,8,13,. Writea programthat
    computesthenthFibonaccinumberwheren is a valueinputbytheuser. Forexample,if n = 6, thenthe
    resultis 8.Note:Fibonaccinumbersgrow veryrapidly;yourprogramshouldbeabletohandlevery
    largenumbers.

  2. Youhave seenthatthemathlibrarycontainsa functionthatcomputesthesquarerootofnumbers.In
    thisexercise,youaretowriteyourownalgorithmforcomputingsquareroots.Onewaytosolve this
    problemis tousea guess-and-checkapproach.Youfirstguesswhatthesquarerootmightbeandthen
    seehow closeyourguessis.Youcanusethisinformationto make anotherguessandcontinueguessing
    untilyouhave foundthesquareroot(ora closeapproximationtoit). Oneparticularlygoodwayof
    makingguessesis touseNewton’s method.Supposexis thenumberwewanttherootof,andguess
    is thecurrentguessedanswer. Theguesscanbeimprovedbyusing


guess guessx
2 asthenextguess.
Writea programthatimplementsNewton’s method.Theprogramshouldprompttheuserforthevalue
to findthesquarerootof(x) andthenumberoftimesto improve theguess.Startingwithaguessvalue
ofx/2, yourprogramshouldloopthespecifiednumberoftimesapplyingNewton’s methodandreport
thefinalvalueofguess. Youmightalsoprintoutthevalueofmath.sqrt(x)forcomparison.
Free download pdf