Python Programming: An Introduction to Computer Science

(Nora) #1
11.7. EXERCISES 199

(a)s1 + s2
(b)3 * s1 + 2 * s2
(c)s1[1]
(d)s1[1:3]
(e)s1 + s2[-1]


  1. Giventhesameinitialstatementsasinthepreviousproblem,showthevaluesofs1ands2after
    executingeachofthefollowingstatements.Treateachpartindependently(i.e.,assumethats1ands2
    startwiththeiroriginalvalueseachtime).


(a)s1.remove(2)
(b)s1.sort().reverse()
(c)s1.append([s2.index(’b’)])
(d)s2.pop(s1.pop(2))
(e)s2.insert(s1[0],’d’)


  1. Modifythestatisticspackagefromthechaptersothatclientprogramshave moreflexibilityincom-
    putingthemeanand/orstandarddeviation. Specifically, redesignthelibrarytohave thefollowing
    functions:


mean(nums)Returnsthemeanofnumbersinnums.
stdDev(nums)Returnsthestandarddeviationofnums.
meanStdDev(nums)Returnsboththemeanandstandarddeviationofnums.


  1. Mostlanguagesdonothave theflexiblebuilt-inlist(array)operationsthatPythonhas.Writeanalgo-
    rithmforeachofthefollowingPythonoperationsandtestyouralgorithmbywritingit upina suitable
    function.Forexample,asa function,reverse(myList)shoulddothesameasmyList.reverse().
    Obviously, youarenotallowedtousethecorrespondingPythonmethodtoimplementyourfunction.


(a)count(myList, x)(likemyList.count(x))
(b)isin(myList, x)(likex in myList))
(c)index(myList, x)(likemyList.index(x))
(d)reverse(myList)(likemyList.reverse())
(e)sort(myList)(likemyList.sort())


  1. Writeandtesta functionshuffle(myList)thatscramblesa listintoa randomorder, like shuffling
    a deckofcards.

  2. TheSieve ofEratosthenesis anelegantalgorithmforfindingalloftheprimenumbersuptosomelimit
    n. Thebasicideais tofirstcreatea listofnumbersfrom2 ton. Thefirstnumberis removedfromthe
    list,andannouncedasa primenumber, andallmultiplesofthisnumberuptonareremovedfromthe
    list.Thisprocesscontinuesuntilthelistis empty.
    Forexample,if wewishedtofindalltheprimesupto10,thelistwouldoriginallycontain2,3,4,5,
    6,7,8,9,10.The2 is removedandannouncedtobeprime.Then4,6,8 and 10 areremoved,since
    they aremultiplesof2. Thatleaves3,5,7,9. Repeatingtheprocess,3 is announcedasprimeand
    removed,and9 is removedbecauseit is a multipleof3.Thatleaves5 and7.Thealgorithmcontinues
    byannouncingthat5 is primeandremovingit fromthelist.Finally, 7 is announcedandremoved,and
    we’redone.
    Writea programthatpromptsa userfornandthenusesthesieve algorithmtofindalltheprimesless
    thanorequalton.

  3. CreateandtestaSetclassto representa classicalset.Yoursetsshouldsupportthefollowingmethods:

Free download pdf