Python Programming: An Introduction to Computer Science

(Nora) #1
58 CHAPTER4. COMPUTINGWITHSTRINGS

(d)msg = ""
for s in string.split("secret","e"):
msg = msg + s
print msg
(e)msg = ""
for ch in "secret":
msg = msg + chr(ord(ch)+1)
print msg


  1. Show thestringthatwouldresultfromeachofthefollowingstringformattingoperations.If theoper-
    ationis notlegal,explainwhy.


(a)"Looks like %s and%s for breakfast" % ("spam", "eggs")
(b)"There is %d %s %d %s" % (1,"spam", 4, "you")
(c)"Hello %s" % ("Suzie","Programmer")
(d)"%0.2f %0.2f" % (2.3,2.3468)
(e)"%7.5f %7.5f" % (2.3,2.3468)
(f)"Time left %02d:%05.2f"% (1, 37.374)
(g)"%3d" % ("14")


  1. Explainwhypublickey encryptionis moreusefulforsecuringcommunicationsontheInternetthan
    private(shared)key encryption.

  2. A certainCSprofessorgives5-pointquizzesthataregradedonthescale5-A,4-B,3-C,2-D,1-F, 0-F.
    Writea programthatacceptsa quizscoreasaninputandprintsoutthecorrespondinggrade.

  3. AcertainCSprofessorgives100-pointexamsthataregradedonthescale90–100:A,80–89:B,70–
    79:C,60–69:D, 60:F. Writea programthatacceptsanexamscoreasinputandprintsoutthecorre-
    spondinggrade.

  4. Anacronymis a wordformedbytakingthefirstlettersofthewordsina phraseandmakinga word
    fromthem. Forexample,RAMis anacronymfor“randomaccessmemory.” Writea programthat
    allowstheusertotypeina phraseandoutputstheacronymforthatphrase.Note:theacronymshould
    bealluppercase,evenif thewordsinthephrasearenotcapitalized.

  5. Numerologistsclaimtobeabletodeterminea person’s charactertraitsbasedonthe“numericvalue”
    ofa name.Thevalueofa nameis determinedbysummingupthevaluesofthelettersofthename
    where’a’is 1,’b’is 2,’c’is 3 etc.,upto’z’being26.Forexample,thename“Zelle”wouldhave the
    value 26  5  12  12  5 60 (whichhappenstobea veryauspiciousnumber, bytheway).Writea
    programthatcalculatesthenumericvalueofa singlenameprovidedasinput.

  6. Expandyoursolutionto thepreviousproblemto allow thecalculationofa completenamesuchas“John
    MarvinZelle”or“JohnJacobJingleheimerSmith.” Thetotalvalueis justthesumofthenumericvalue
    foreachname.

  7. A Caesarcipheris a simplesubstitutioncipherbasedontheideaofshiftingeachletteroftheplaintext
    messagea fixednumber(calledthekey)ofpositionsinthealphabet.Forexample,if thekey valueis
    2,theword“Sourpuss”wouldbeencodedas“Uqwtrwuu.” Theoriginalmessagecanberecoveredby
    “reencoding”it usingthenegative ofthekey.
    Writea programthatcanencodeanddecodeCaesarciphers.Theinputtotheprogramwillbea string
    ofplaintextandthevalueofthekey. Theoutputwillbeanencodedmessagewhereeachcharacterin
    theoriginalmessageis replacedbyshiftingit key charactersintheASCIIcharacterset.Forexample,
    ifchis a characterinthestringandkeyis theamounttoshift,thenthecharacterthatreplaceschcan
    becalculatedas:chr(ord(ch)+ key).

Free download pdf