Python-programming-exercises_100+ Python challenging programming exercises

Embed Size (px)

DESCRIPTION

100+ python questions.

Citation preview

  • Explore Features Enterprise Blog

    Pythonprogrammingexercises/100+Pythonchallengingprogrammingexercises.txt

    1contributor

    xinlincaoonJun21,2012addedmorequestions

    Signup SigninSearch

    55 76Star Forkzhiwehu / Pythonprogrammingexercises

    masterbranch:

    2377lines(1585sloc) 51.343kb

    1234567891011121314151617181920212223242526272829303132

    3334353637383940414243444546474849505152535455

    Raw Blame History

    100+Pythonchallengingprogrammingexercises

    1. LeveldescriptionLevel DescriptionLevel1BeginnermeanssomeonewhohasjustgonethroughanintroductoryPythoncourse.Hecansolvesomeproblemswith1or2Pythonclassesorfunctions.Normally,theanswerscoulddirectlybefoundinthetextbooks.Level2IntermediatemeanssomeonewhohasjustlearnedPython,butalreadyhasarelativelystrongprogrammingbackgroundfrombefore.Heshouldbeabletosolveproblemswhichmayinvolve3or3Pythonclassesorfunctions.Theanswerscannotbedirectlybefoundinthetextbooks.Level3Advanced.HeshouldusePythontosolvemorecomplexproblemusingmorerichlibrariesfunctionsanddatastructuresandalgorithms.HeissupposedtosolvetheproblemusingseveralPythonstandardpackagesandadvancedtechniques.

    2. Problemtemplate

    ##QuestionHintsSolution

    3. Questions

    ##Question1Level1

    Question:Writeaprogramwhichwillfindallsuchnumberswhicharedivisibleby7butarenotamultipleof5,between2000and3200(bothincluded).Thenumbersobtainedshouldbeprintedinacommaseparatedsequenceonasingleline.

    Hints:Consideruserange(#begin,#end)method

    Solution:l=[]foriinrange(2000,3201):

    if(i%7==0)and(i%5!=0):l.append(str(i))

    print','.join(l)##

    ##Question2Level1

    Question:Writeaprogramwhichcancomputethefactorialofagivennumbers.Theresultsshouldbeprintedinacommaseparatedsequenceonasingleline.Supposethefollowinginputissuppliedtotheprogram:8Then,theoutputshouldbe:40320

    Hints:Incaseofinputdatabeingsuppliedtothequestion,itshouldbeassumedtobeaconsoleinput.

    Solution:deffact(x):

    Thisrepository

  • 565758596061626364656667686970717273747576777879808182

    83

    84858687888990919293949596979899

    100101102103104105106107108109110111112113114115116117118119120121122123124125126127128

    ifx==0:return1returnx*fact(x1)

    x=int(raw_input())printfact(x)##

    ##Question3Level1

    Question:Withagivenintegralnumbern,writeaprogramtogenerateadictionarythatcontains(i,i*i)suchthatisanintegralnumberbetween1andn(bothincluded).andthentheprogramshouldprintthedictionary.Supposethefollowinginputissuppliedtotheprogram:8Then,theoutputshouldbe:{1:1,2:4,3:9,4:16,5:25,6:36,7:49,8:64}

    Hints:Incaseofinputdatabeingsuppliedtothequestion,itshouldbeassumedtobeaconsoleinput.Considerusedict()

    Solution:n=int(raw_input())d=dict()foriinrange(1,n+1):

    d[i]=i*i

    printd##

    ##Question4Level1

    Question:Writeaprogramwhichacceptsasequenceofcommaseparatednumbersfromconsoleandgeneratealistandatuplewhichcontainseverynumber.Supposethefollowinginputissuppliedtotheprogram:34,67,55,33,12,98Then,theoutputshouldbe:['34','67','55','33','12','98']('34','67','55','33','12','98')

    Hints:Incaseofinputdatabeingsuppliedtothequestion,itshouldbeassumedtobeaconsoleinput.tuple()methodcanconvertlisttotuple

    Solution:values=raw_input()l=values.split(",")t=tuple(l)printlprintt##

    ##Question5Level1

    Question:Defineaclasswhichhasatleasttwomethods:getString:togetastringfromconsoleinputprintString:toprintthestringinuppercase.Alsopleaseincludesimpletestfunctiontotesttheclassmethods.

    Hints:Use__init__methodtoconstructsomeparameters

    Solution:classInputOutString(object):def__init__(self):self.s=""

  • 129130131132

    133134

    135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182

    183184185

    186187188189190191192193194195196197198199200201

    defgetString(self):self.s=raw_input()

    defprintString(self):printself.s.upper()

    strObj=InputOutString()strObj.getString()strObj.printString()##

    ##Question6Level2

    Question:Writeaprogramthatcalculatesandprintsthevalueaccordingtothegivenformula:Q=Squarerootof[(2*C*D)/H]FollowingarethefixedvaluesofCandH:Cis50.His30.Disthevariablewhosevaluesshouldbeinputtoyourprograminacommaseparatedsequence.ExampleLetusassumethefollowingcommaseparatedinputsequenceisgiventotheprogram:100,150,180Theoutputoftheprogramshouldbe:18,22,24

    Hints:Iftheoutputreceivedisindecimalform,itshouldberoundedofftoitsnearestvalue(forexample,iftheoutputreceivedis26.0,itshouldbeprintedas26)Incaseofinputdatabeingsuppliedtothequestion,itshouldbeassumedtobeaconsoleinput.

    Solution:#!/usr/bin/envpythonimportmathc=50h=30value=[]items=[xforxinraw_input().split(',')]fordinitems:value.append(str(int(round(math.sqrt(2*c*float(d)/h)))))

    print','.join(value)##

    ##Question7Level2

    Question:Writeaprogramwhichtakes2digits,X,Yasinputandgeneratesa2dimensionalarray.Theelementvalueintheithrowandjthcolumnofthearrayshouldbei*j.Note:i=0,1..,X1;j=0,1,Y1.ExampleSupposethefollowinginputsaregiventotheprogram:

    3,5Then,theoutputoftheprogramshouldbe:[[0,0,0,0,0],[0,1,2,3,4],[0,2,4,6,8]]

    Hints:Note:Incaseofinputdatabeingsuppliedtothequestion,itshouldbeassumedtobeaconsoleinputinacommaseparatedform.

    Solution:input_str=raw_input()dimensions=[int(x)forxininput_str.split(',')]rowNum=dimensions[0]colNum=dimensions[1]multilist=[[0forcolinrange(colNum)]forrowinrange(rowNum)]

    forrowinrange(rowNum):forcolinrange(colNum):multilist[row][col]=row*col

    printmultilist

  • 202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232

    233234235236

    237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275

    ##

    ##Question8Level2

    Question:Writeaprogramthatacceptsacommaseparatedsequenceofwordsasinputandprintsthewordsinacommaseparatedsequenceaftersortingthemalphabetically.Supposethefollowinginputissuppliedtotheprogram:without,hello,bag,worldThen,theoutputshouldbe:bag,hello,without,world

    Hints:Incaseofinputdatabeingsuppliedtothequestion,itshouldbeassumedtobeaconsoleinput.

    Solution:items=[xforxinraw_input().split(',')]items.sort()print','.join(items)##

    ##Question9Level2

    QuestionWriteaprogramthatacceptssequenceoflinesasinputandprintsthelinesaftermakingallcharactersinthesentencecapitalized.Supposethefollowinginputissuppliedtotheprogram:HelloworldPracticemakesperfect

    Then,theoutputshouldbe:HELLOWORLDPRACTICEMAKESPERFECT

    Hints:Incaseofinputdatabeingsuppliedtothequestion,itshouldbeassumedtobeaconsoleinput.

    Solution:lines=[]whileTrue:s=raw_input()ifs:lines.append(s.upper())else:break;

    forsentenceinlines:printsentence##

    ##Question10Level2

    Question:Writeaprogramthatacceptsasequenceofwhitespaceseparatedwordsasinputandprintsthewordsafterremovingallduplicatewordsandsortingthemalphanumerically.Supposethefollowinginputissuppliedtotheprogram:helloworldandpracticemakesperfectandhelloworldagainThen,theoutputshouldbe:againandhellomakesperfectpracticeworld

    Hints:Incaseofinputdatabeingsuppliedtothequestion,itshouldbeassumedtobeaconsoleinput.Weusesetcontainertoremoveduplicateddataautomaticallyandthenusesorted()tosortthedata.

    Solution:s=raw_input()words=[wordforwordins.split("")]print"".join(sorted(list(set(words))))##

    ##Question11

  • 276277278279280281282

    283284285286287

    288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332

    333334335336337338

    339340341342343344345346347348

    Level2

    Question:Writeaprogramwhichacceptsasequenceofcommaseparated4digitbinarynumbersasitsinputandthencheckwhethertheyaredivisibleby5ornot.Thenumbersthataredivisibleby5aretobeprintedinacommaseparatedsequence.Example:0100,0011,1010,1001Thentheoutputshouldbe:

    1010Notes:Assumethedataisinputbyconsole.

    Hints:Incaseofinputdatabeingsuppliedtothequestion,itshouldbeassumedtobeaconsoleinput.

    Solution:value=[]items=[xforxinraw_input().split(',')]forpinitems:intp=int(p,2)ifnotintp%5:value.append(p)

    print','.join(value)##

    ##Question12Level2

    Question:Writeaprogram,whichwillfindallsuchnumbersbetween1000and3000(bothincluded)suchthateachdigitofthenumberisanevennumber.Thenumbersobtainedshouldbeprintedinacommaseparatedsequenceonasingleline.

    Hints:Incaseofinputdatabeingsuppliedtothequestion,itshouldbeassumedtobeaconsoleinput.

    Solution:values=[]foriinrange(1000,3001):s=str(i)if(int(s[0])%2==0)and(int(s[1])%2==0)and(int(s[2])%2==0)and(int(s[3])%2==0):values.append(s)print",".join(values)##

    ##Question13Level2

    Question:Writeaprogramthatacceptsasentenceandcalculatethenumberoflettersanddigits.Supposethefollowinginputissuppliedtotheprogram:helloworld!123Then,theoutputshouldbe:LETTERS10DIGITS3

    Hints:

    Incaseofinputdatabeingsuppliedtothequestion,itshouldbeassumedtobeaconsoleinput.

    Solution:s=raw_input()d={"DIGITS":0,"LETTERS":0}forcins:

    ifc.isdigit():d["DIGITS"]+=1elifc.isalpha():d["LETTERS"]+=1else:passprint"LETTERS",d["LETTERS"]print"DIGITS",d["DIGITS"]##

  • 349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382

    383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422

    ##Question14Level2

    Question:Writeaprogramthatacceptsasentenceandcalculatethenumberofuppercaselettersandlowercaseletters.Supposethefollowinginputissuppliedtotheprogram:Helloworld!Then,theoutputshouldbe:UPPERCASE1LOWERCASE9

    Hints:Incaseofinputdatabeingsuppliedtothequestion,itshouldbeassumedtobeaconsoleinput.

    Solution:s=raw_input()d={"UPPERCASE":0,"LOWERCASE":0}forcins:ifc.isupper():d["UPPERCASE"]+=1elifc.islower():d["LOWERCASE"]+=1else:passprint"UPPERCASE",d["UPPERCASE"]print"LOWERCASE",d["LOWERCASE"]##

    ##Question15Level2

    Question:

    Writeaprogramthatcomputesthevalueofa+aa+aaa+aaaawithagivendigitasthevalueofa.Supposethefollowinginputissuppliedtotheprogram:9Then,theoutputshouldbe:11106

    Hints:Incaseofinputdatabeingsuppliedtothequestion,itshouldbeassumedtobeaconsoleinput.

    Solution:a=raw_input()n1=int("%s"%a)n2=int("%s%s"%(a,a))n3=int("%s%s%s"%(a,a,a))n4=int("%s%s%s%s"%(a,a,a,a))printn1+n2+n3+n4##

    ##Question16Level2

    Question:Usealistcomprehensiontosquareeachoddnumberinalist.Thelistisinputbyasequenceofcommaseparatednumbers.Supposethefollowinginputissuppliedtotheprogram:1,2,3,4,5,6,7,8,9Then,theoutputshouldbe:1,3,5,7,9

    Hints:Incaseofinputdatabeingsuppliedtothequestion,itshouldbeassumedtobeaconsoleinput.

    Solution:values=raw_input()numbers=[xforxinvalues.split(",")ifint(x)%2!=0]print",".join(numbers)##

    Question17Level2

  • 423424425426427428429430431432

    433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482

    483484485486487488489490

    491492493494

    Question:Writeaprogramthatcomputesthenetamountofabankaccountbasedatransactionlogfromconsoleinput.Thetransactionlogformatisshownasfollowing:D100W200DmeansdepositwhileWmeanswithdrawal.Supposethefollowinginputissuppliedtotheprogram:D300D300

    W200D100Then,theoutputshouldbe:500

    Hints:Incaseofinputdatabeingsuppliedtothequestion,itshouldbeassumedtobeaconsoleinput.

    Solution:importsysnetAmount=0whileTrue:s=raw_input()ifnots:breakvalues=s.split("")operation=values[0]amount=int(values[1])ifoperation=="D":netAmount+=amountelifoperation=="W":netAmount=amountelse:passprintnetAmount##

    ##Question18Level3

    Question:Awebsiterequirestheuserstoinputusernameandpasswordtoregister.Writeaprogramtocheckthevalidityofpasswordinputbyusers.Followingarethecriteriaforcheckingthepassword:1.Atleast1letterbetween[az]2.Atleast1numberbetween[09]1.Atleast1letterbetween[AZ]3.Atleast1characterfrom[$#@]4.Minimumlengthoftransactionpassword:65.Maximumlengthoftransactionpassword:12Yourprogramshouldacceptasequenceofcommaseparatedpasswordsandwillcheckthemaccordingtotheabovecriteria.Passwordsthatmatchthecriteriaaretobeprinted,eachseparatedbyacomma.ExampleIfthefollowingpasswordsaregivenasinputtotheprogram:ABd1234@1,aF1#,2w3E*,2We3345Then,theoutputoftheprogramshouldbe:ABd1234@1

    Hints:Incaseofinputdatabeingsuppliedtothequestion,itshouldbeassumedtobeaconsoleinput.

    Solutions:importrevalue=[]items=[xforxinraw_input().split(',')]forpinitems:iflen(p)12:continueelse:

    passifnotre.search("[az]",p):continueelifnotre.search("[09]",p):

  • 495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541

    542543544545546547548549550551552553554555556557558559560561562563564565566567568

    continueelifnotre.search("[AZ]",p):continueelifnotre.search("[$#@]",p):continueelifre.search("\s",p):continueelse:passvalue.append(p)print",".join(value)##

    ##Question19Level3

    Question:Youarerequiredtowriteaprogramtosortthe(name,age,height)tuplesbyascendingorderwherenameisstring,ageandheightarenumbers.Thetuplesareinputbyconsole.Thesortcriteriais:1:Sortbasedonname;2:Thensortbasedonage;3:Thensortbyscore.Thepriorityisthatname>age>score.Ifthefollowingtuplesaregivenasinputtotheprogram:Tom,19,80John,20,90Jony,17,91Jony,17,93Json,21,85Then,theoutputoftheprogramshouldbe:[('John','20','90'),('Jony','17','91'),('Jony','17','93'),('Json','21','85'),('Tom','19','80')]

    Hints:Incaseofinputdatabeingsuppliedtothequestion,itshouldbeassumedtobeaconsoleinput.Weuseitemgettertoenablemultiplesortkeys.

    Solutions:fromoperatorimportitemgetter,attrgetter

    l=[]whileTrue:s=raw_input()ifnots:breakl.append(tuple(s.split(",")))

    printsorted(l,key=itemgetter(0,1,2))

    ##

    ##Question20Level3

    Question:Defineaclasswithageneratorwhichcaniteratethenumbers,whicharedivisibleby7,betweenagivenrange0andn.

    Hints:Consideruseyield

    Solution:defputNumbers(n):i=0whilei

  • 569570571572573574575576577578579580581582583584585586587588589590591592

    593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632

    633634635636637638639640641642

    Level3

    QuestionArobotmovesinaplanestartingfromtheoriginalpoint(0,0).TherobotcanmovetowardUP,DOWN,LEFTandRIGHTwithagivensteps.Thetraceofrobotmovementisshownasthefollowing:UP5DOWN3LEFT3RIGHT2Thenumbersafterthedirectionaresteps.Pleasewriteaprogramtocomputethedistancefromcurrentpositionafterasequenceofmovementandoriginalpoint.Ifthedistanceisafloat,thenjustprintthenearestinteger.Example:Ifthefollowingtuplesaregivenasinputtotheprogram:UP5DOWN3LEFT3RIGHT2Then,theoutputoftheprogramshouldbe:2

    Hints:Incaseofinputdatabeingsuppliedtothequestion,itshouldbeassumedtobeaconsoleinput.

    Solution:importmath

    pos=[0,0]whileTrue:s=raw_input()ifnots:breakmovement=s.split("")direction=movement[0]steps=int(movement[1])ifdirection=="UP":pos[0]+=stepselifdirection=="DOWN":pos[0]=stepselifdirection=="LEFT":pos[1]=stepselifdirection=="RIGHT":pos[1]+=stepselse:pass

    printint(round(math.sqrt(pos[1]**2+pos[0]**2)))##

    ##Question22Level3

    Question:Writeaprogramtocomputethefrequencyofthewordsfromtheinput.Theoutputshouldoutputaftersortingthekeyalphanumerically.Supposethefollowinginputissuppliedtotheprogram:NewtoPythonorchoosingbetweenPython2andPython3?ReadPython2orPython3.Then,theoutputshouldbe:2:23.:13?:1New:1Python:5Read:1and:1between:1choosing:1

    or:2to:1

    HintsIncaseofinputdatabeingsuppliedtothequestion,itshouldbeassumedtobeaconsoleinput.

    Solution:freq={}#frequencyofwordsintextline=raw_input()forwordinline.split():

  • 643

    644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682

    683684685686687688689690691692693694

    695696697698699700701702703704705706707708709710711712713714715

    freq[word]=freq.get(word,0)+1

    words=freq.keys()words.sort()

    forwinwords:print"%s:%d"%(w,freq[w])##

    ##Question23level1

    Question:Writeamethodwhichcancalculatesquarevalueofnumber

    Hints:Usingthe**operator

    Solution:defsquare(num):returnnum**2

    printsquare(2)printsquare(3)##

    ##Question24Level1

    Question:Pythonhasmanybuiltinfunctions,andifyoudonotknowhowtouseit,youcanreaddocumentonlineorfindsomebooks.ButPythonhasabuiltindocumentfunctionforeverybuiltinfunctions.PleasewriteaprogramtoprintsomePythonbuiltinfunctionsdocuments,suchasabs(),int(),raw_input()AndadddocumentforyourownfunctionHints:Thebuiltindocumentmethodis__doc__

    Solution:

    printabs.__doc__printint.__doc__printraw_input.__doc__

    defsquare(num):'''Returnthesquarevalueoftheinputnumber.Theinputnumbermustbeinteger.'''returnnum**2

    printsquare(2)

    printsquare.__doc__##

    ##Question25Level1

    Question:Defineaclass,whichhaveaclassparameterandhaveasameinstanceparameter.

    Hints:Defineainstanceparameter,needadditin__init__methodYoucaninitaobjectwithconstructparameterorsetthevaluelater

    Solution:classPerson:#Definetheclassparameter"name"name="Person"def__init__(self,name=None):#self.nameistheinstanceparameter

  • 716717718719720721722723724725726727728729730731732

    733734735736737738739740741742743744745

    746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782

    783784785786787788

    self.name=name

    jeffrey=Person("Jeffrey")print"%snameis%s"%(Person.name,jeffrey.name)

    nico=Person()nico.name="Nico"print"%snameis%s"%(Person.name,nico.name)##

    ##Question:Defineafunctionwhichcancomputethesumoftwonumbers.

    Hints:Defineafunctionwithtwonumbersasarguments.Youcancomputethesuminthefunctionandreturnthevalue.

    SolutiondefSumFunction(number1,number2): returnnumber1+number2

    printSumFunction(1,2)

    ##Question:Defineafunctionthatcanconvertaintegerintoastringandprintitinconsole.

    Hints:

    Usestr()toconvertanumbertostring.

    SolutiondefprintValue(n): printstr(n)

    printValue(3)

    ##Question:Defineafunctionthatcanconvertaintegerintoastringandprintitinconsole.

    Hints:

    Usestr()toconvertanumbertostring.

    SolutiondefprintValue(n): printstr(n)

    printValue(3)

    ##2.10

    Question:Defineafunctionthatcanreceivetwointegralnumbersinstringformandcomputetheirsumandthenprintitinconsole.

    Hints:

    Useint()toconvertastringtointeger.

    SolutiondefprintValue(s1,s2): printint(s1)+int(s2)

    printValue("3","4")#7

    ##2.10

  • 789790791792793794795796

    797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832

    833834835836837838839840841842843844845846847

    848849850851852853854855856857858859860861

    Question:Defineafunctionthatcanaccepttwostringsasinputandconcatenatethemandthenprintitinconsole.

    Hints:

    Use+toconcatenatethestrings

    Solution

    defprintValue(s1,s2): prints1+s2

    printValue("3","4")#34

    ##2.10

    Question:Defineafunctionthatcanaccepttwostringsasinputandprintthestringwithmaximumlengthinconsole.Iftwostringshavethesamelength,thenthefunctionshouldprintallstringslinebyline.

    Hints:

    Uselen()functiontogetthelengthofastring

    SolutiondefprintValue(s1,s2): len1=len(s1) len2=len(s2) iflen1>len2: prints1 eliflen2>len1: prints2 else: prints1 prints2

    printValue("one","three")

    ##2.10

    Question:Defineafunctionthatcanacceptanintegernumberasinputandprintthe"Itisanevennumber"ifthenumberiseven,otherwiseprint"Itisanoddnumber".

    Hints:

    Use%operatortocheckifanumberisevenorodd.

    SolutiondefcheckValue(n): ifn%2==0: print"Itisanevennumber" else: print"Itisanoddnumber"

    checkValue(7)

    ##2.10

    Question:Defineafunctionwhichcanprintadictionarywherethekeysarenumbersbetween1and3(bothincluded)andthevaluesaresquareofkeys.

    Hints:

    Usedict[key]=valuepatterntoputentryintoadictionary.Use**operatortogetpowerofanumber.

  • 862863864865866867868869870871872873874875876877878879880881882

    883884885886887888889890891892893894895896897898

    899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932

    933934

    SolutiondefprintDict(): d=dict() d[1]=1 d[2]=2**2 d[3]=3**2 printd

    printDict()

    ##2.10

    Question:Defineafunctionwhichcanprintadictionarywherethekeysarenumbersbetween1and20(bothincluded)andthevaluesaresquareofkeys.

    Hints:

    Usedict[key]=valuepatterntoputentryintoadictionary.Use**operatortogetpowerofanumber.Userange()forloops.

    SolutiondefprintDict(): d=dict() foriinrange(1,21): d[i]=i**2 printd

    printDict()

    ##2.10

    Question:Defineafunctionwhichcangenerateadictionarywherethekeysarenumbersbetween1and20(bothincluded)andthevaluesaresquareofkeys.Thefunctionshouldjustprintthevaluesonly.

    Hints:

    Usedict[key]=valuepatterntoputentryintoadictionary.Use**operatortogetpowerofanumber.Userange()forloops.Usekeys()toiteratekeysinthedictionary.Alsowecanuseitem()togetkey/valuepairs.

    SolutiondefprintDict(): d=dict() foriinrange(1,21): d[i]=i**2 for(k,v)ind.items(): printv

    printDict()

    ##2.10

    Question:Defineafunctionwhichcangenerateadictionarywherethekeysarenumbersbetween1and20(bothincluded)andthevaluesaresquareofkeys.Thefunctionshouldjustprintthekeysonly.

    Hints:

    Usedict[key]=valuepatterntoputentryintoadictionary.

    Use**operatortogetpowerofanumber.Userange()forloops.

  • 935936937938939940941942943944945946947948949

    950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982

    9839849859869879889899909919929939949959969979989991000

    1001100210031004100510061007

    Usekeys()toiteratekeysinthedictionary.Alsowecanuseitem()togetkey/valuepairs.

    SolutiondefprintDict(): d=dict() foriinrange(1,21): d[i]=i**2 forkind.keys(): printk

    printDict()

    ##

    2.10

    Question:Defineafunctionwhichcangenerateandprintalistwherethevaluesaresquareofnumbersbetween1and20(bothincluded).

    Hints:

    Use**operatortogetpowerofanumber.Userange()forloops.Uselist.append()toaddvaluesintoalist.

    SolutiondefprintList(): li=list() foriinrange(1,21): li.append(i**2) printli

    printList()

    ##2.10

    Question:Defineafunctionwhichcangeneratealistwherethevaluesaresquareofnumbersbetween1and20(bothincluded).Thenthefunctionneedstoprintthefirst5elementsinthelist.

    Hints:

    Use**operatortogetpowerofanumber.Userange()forloops.Uselist.append()toaddvaluesintoalist.Use[n1:n2]toslicealist

    SolutiondefprintList(): li=list() foriinrange(1,21): li.append(i**2) printli[:5]

    printList()

    ##2.10

    Question:Defineafunctionwhichcangeneratealistwherethevaluesaresquareofnumbersbetween1and20(bothincluded).Thenthefunctionneedstoprintthelast5elementsinthelist.

    Hints:

    Use**operatortogetpowerofanumber.Userange()forloops.Uselist.append()toaddvaluesintoalist.Use[n1:n2]toslicealist

  • 1008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032

    1033103410351036103710381039104010411042104310441045104610471048104910501051

    105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081

    SolutiondefprintList(): li=list() foriinrange(1,21): li.append(i**2) printli[5:]

    printList()

    ##2.10

    Question:Defineafunctionwhichcangeneratealistwherethevaluesaresquareofnumbersbetween1and20(bothincluded).Thenthefunctionneedstoprintallvaluesexceptthefirst5elementsinthelist.

    Hints:

    Use**operatortogetpowerofanumber.Userange()forloops.Uselist.append()toaddvaluesintoalist.Use[n1:n2]toslicealist

    Solution

    defprintList(): li=list() foriinrange(1,21): li.append(i**2) printli[5:]

    printList()

    ##2.10

    Question:Defineafunctionwhichcangenerateandprintatuplewherethevaluearesquareofnumbersbetween1and20(bothincluded).

    Hints:

    Use**operatortogetpowerofanumber.

    Userange()forloops.Uselist.append()toaddvaluesintoalist.Usetuple()togetatuplefromalist.

    SolutiondefprintTuple(): li=list() foriinrange(1,21): li.append(i**2) printtuple(li) printTuple()

    ##2.10

    Question:Withagiventuple(1,2,3,4,5,6,7,8,9,10),writeaprogramtoprintthefirsthalfvaluesinonelineandthelasthalfvaluesinoneline.

    Hints:

    Use[n1:n2]notationtogetaslicefromatuple.

    Solutiontp=(1,2,3,4,5,6,7,8,9,10)tp1=tp[:5]tp2=tp[5:]printtp1

  • 1082

    10831084108510861087108810891090109110921093109410951096109710981099110011011102

    110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132

    113311341135113611371138113911401141114211431144114511461147114811491150115111521153

    1154

    printtp2

    ##2.10

    Question:Writeaprogramtogenerateandprintanothertuplewhosevaluesareevennumbersinthegiventuple(1,2,3,4,5,6,7,8,9,10).

    Hints:

    Use"for"toiteratethetupleUsetuple()togenerateatuplefromalist.

    Solutiontp=(1,2,3,4,5,6,7,8,9,10)li=list()foriintp: iftp[i]%2==0: li.append(tp[i])

    tp2=tuple(li)printtp2

    ##2.14

    Question:Writeaprogramwhichacceptsastringasinputtoprint"Yes"ifthestringis"yes"or"YES"or"Yes",otherwiseprint"No".

    Hints:

    Useifstatementtojudgecondition.

    Solutions=raw_input()ifs=="yes"ors=="YES"ors=="Yes":print"Yes"else:print"No"

    ##3.4

    Question:Writeaprogramwhichcanfilterevennumbersinalistbyusingfilterfunction.Thelistis:[1,2,3,4,5,6,7,8,9,10].

    Hints:

    Usefilter()tofiltersomeelementsinalist.Uselambdatodefineanonymousfunctions.

    Solutionli=[1,2,3,4,5,6,7,8,9,10]evenNumbers=filter(lambdax:x%2==0,li)printevenNumbers

    ##3.4

    Question:Writeaprogramwhichcanmap()tomakealistwhoseelementsaresquareofelementsin[1,2,3,4,5,6,7,8,9,10].

    Hints:

    Usemap()togeneratealist.Uselambdatodefineanonymousfunctions.

  • 1155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182

    1183118411851186118711881189119011911192119311941195119611971198119912001201120212031204

    120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228

    Solutionli=[1,2,3,4,5,6,7,8,9,10]squaredNumbers=map(lambdax:x**2,li)printsquaredNumbers

    ##3.5

    Question:Writeaprogramwhichcanmap()andfilter()tomakealistwhoseelementsaresquareofevennumberin[1,2,3,4,5,6,7,8,9,10].

    Hints:

    Usemap()togeneratealist.Usefilter()tofilterelementsofalist.Uselambdatodefineanonymousfunctions.

    Solutionli=[1,2,3,4,5,6,7,8,9,10]evenNumbers=map(lambdax:x**2,filter(lambdax:x%2==0,li))printevenNumbers

    ##3.5

    Question:Writeaprogramwhichcanfilter()tomakealistwhoseelementsareevennumberbetween1and20(bothincluded).

    Hints:

    Usefilter()tofilterelementsofalist.Uselambdatodefineanonymousfunctions.

    SolutionevenNumbers=filter(lambdax:x%2==0,range(1,21))printevenNumbers

    ##3.5

    Question:Writeaprogramwhichcanmap()tomakealistwhoseelementsaresquareofnumbersbetween1and20(bothincluded).

    Hints:

    Usemap()togeneratealist.

    Uselambdatodefineanonymousfunctions.

    SolutionsquaredNumbers=map(lambdax:x**2,range(1,21))printsquaredNumbers

    ##7.2

    Question:DefineaclassnamedAmericanwhichhasastaticmethodcalledprintNationality.

    Hints:

    Use@staticmethoddecoratortodefineclassstaticmethod.

    SolutionclassAmerican(object):@staticmethoddefprintNationality():print"America"

  • 1229123012311232

    12331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255

    125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282

    1283128412851286128712881289129012911292129312941295129612971298129913001301

    anAmerican=American()anAmerican.printNationality()American.printNationality()

    ##

    7.2

    Question:DefineaclassnamedAmericananditssubclassNewYorker.

    Hints:

    UseclassSubclass(ParentClass)todefineasubclass.

    Solution:

    classAmerican(object):pass

    classNewYorker(American):pass

    anAmerican=American()aNewYorker=NewYorker()printanAmericanprintaNewYorker

    ##

    7.2

    Question:DefineaclassnamedCirclewhichcanbeconstructedbyaradius.TheCircleclasshasamethodwhichcancomputethearea.

    Hints:

    UsedefmethodName(self)todefineamethod.

    Solution:

    classCircle(object):def__init__(self,r):self.radius=r

    defarea(self):

    returnself.radius**2*3.14

    aCircle=Circle(2)printaCircle.area()

    ##

    7.2

    DefineaclassnamedRectanglewhichcanbeconstructedbyalengthandwidth.TheRectangleclasshasamethodwhichcancomputethearea.

    Hints:

    UsedefmethodName(self)todefineamethod.

  • 1302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332

    1333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375

    Solution:

    classRectangle(object):def__init__(self,l,w):self.length=lself.width=w

    defarea(self):returnself.length*self.width

    aRectangle=Rectangle(2,10)printaRectangle.area()

    ##

    7.2

    DefineaclassnamedShapeanditssubclassSquare.TheSquareclasshasaninitfunctionwhichtakesalengthasargument.BothclasseshaveaareafunctionwhichcanprinttheareaoftheshapewhereShape'sareais0bydefault.

    Hints:

    Tooverrideamethodinsuperclass,wecandefineamethodwiththesamenameinthesuperclass.

    Solution:

    classShape(object):def__init__(self):

    pass

    defarea(self):return0

    classSquare(Shape):def__init__(self,l):Shape.__init__(self)self.length=l

    defarea(self):returnself.length*self.length

    aSquare=Square(3)printaSquare.area()

    ##

    PleaseraiseaRuntimeErrorexception.

    Hints:

    Useraise()toraiseanexception.

    Solution:

    raiseRuntimeError('somethingwrong')

    ##Writeafunctiontocompute5/0andusetry/excepttocatchtheexceptions.

    Hints:

  • 1376137713781379138013811382

    1383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407

    14081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448

    Usetry/excepttocatchexceptions.

    Solution:

    defthrows():return5/0

    try:throws()exceptZeroDivisionError:print"divisionbyzero!"exceptException,err:print'Caughtanexception'finally:print'Infinallyblockforcleanup'

    ##Defineacustomexceptionclasswhichtakesastringmessageasattribute.

    Hints:

    Todefineacustomexception,weneedtodefineaclassinheritedfromException.

    Solution:

    classMyError(Exception):"""Myownexceptionclass

    Attributes:msgexplanationoftheerror"""

    def__init__(self,msg):self.msg=msg

    error=MyError("somethingwrong")

    ##Question:

    Assumingthatwehavesomeemailaddressesinthe"[email protected]"format,pleasewriteprogramtoprinttheusernameofagivenemailaddress.Bothusernamesandcompanynamesarecomposedoflettersonly.

    Example:Ifthefollowingemailaddressisgivenasinputtotheprogram:

    [email protected]

    Then,theoutputoftheprogramshouldbe:

    john

    Incaseofinputdatabeingsuppliedtothequestion,itshouldbeassumedtobeaconsoleinput.

    Hints:

    Use\wtomatchletters.

    Solution:importreemailAddress=raw_input()pat2="(\w+)@((\w+\.)+(com))"r2=re.match(pat2,emailAddress)printr2.group(1)

    ##Question:

    Assumingthatwehavesomeemailaddressesinthe"[email protected]"format,pleasewriteprogramtoprintthecompanynameofagivenemailaddress.Bothusernamesandcompanynamesarecomposedoflettersonly.

    Example:Ifthefollowingemailaddressisgivenasinputtotheprogram:

  • 1449145014511452145314541455145614571458

    145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509

    151015111512151315141515151615171518151915201521

    [email protected]

    Then,theoutputoftheprogramshouldbe:

    google

    Incaseofinputdatabeingsuppliedtothequestion,itshouldbeassumedtobeaconsoleinput.

    Hints:

    Use\wtomatchletters.

    Solution:importreemailAddress=raw_input()pat2="(\w+)@(\w+)\.(com)"r2=re.match(pat2,emailAddress)printr2.group(2)

    ##Question:

    Writeaprogramwhichacceptsasequenceofwordsseparatedbywhitespaceasinputtoprintthewordscomposedofdigitsonly.

    Example:Ifthefollowingwordsisgivenasinputtotheprogram:

    2catsand3dogs.

    Then,theoutputoftheprogramshouldbe:

    ['2','3']

    Incaseofinputdatabeingsuppliedtothequestion,itshouldbeassumedtobeaconsoleinput.

    Hints:

    Usere.findall()tofindallsubstringusingregex.

    Solution:importres=raw_input()printre.findall("\d+",s)

    ##Question:

    Printaunicodestring"helloworld".

    Hints:

    Useu'strings'formattodefineunicodestring.

    Solution:

    unicodeString=u"helloworld!"printunicodeString

    ##WriteaprogramtoreadanASCIIstringandtoconvertittoaunicodestringencodedbyutf8.

    Hints:

    Useunicode()functiontoconvert.

    Solution:

  • 15221523152415251526152715281529153015311532

    1533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560

    1561156215631564156515661567156815691570157115721573157415751576157715781579158015811582

    158315841585158615871588158915901591159215931594

    s=raw_input()u=unicode(s,"utf8")printu

    ##Question:

    WriteaspecialcommenttoindicateaPythonsourcecodefileisinunicode.

    Hints:

    Solution:

    #*coding:utf8*

    ##Question:

    Writeaprogramtocompute1/2+2/3+3/4+...+n/n+1withagivenninputbyconsole(n>0).

    Example:Ifthefollowingnisgivenasinputtotheprogram:

    5

    Then,theoutputoftheprogramshouldbe:

    3.55

    Incaseofinputdatabeingsuppliedtothequestion,itshouldbeassumedtobeaconsoleinput.

    Hints:Usefloat()toconvertanintegertoafloat

    Solution:

    n=int(raw_input())sum=0.0foriinrange(1,n+1):

    sum+=float(float(i)/(i+1))printsum

    ##Question:

    Writeaprogramtocompute:

    f(n)=f(n1)+100whenn>0andf(0)=1

    withagivenninputbyconsole(n>0).

    Example:Ifthefollowingnisgivenasinputtotheprogram:

    5

    Then,theoutputoftheprogramshouldbe:

    500

    Incaseofinputdatabeingsuppliedtothequestion,itshouldbeassumedtobeaconsoleinput.

    Hints:WecandefinerecursivefunctioninPython.

    Solution:

    deff(n):ifn==0:return0else:returnf(n1)+100

  • 15951596159715981599160016011602160316041605160616071608160916101611

    161216131614161516161617161816191620162116221623162416251626162716281629163016311632

    163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662

    16631664166516661667

    n=int(raw_input())printf(n)

    ##

    Question:

    TheFibonacciSequenceiscomputedbasedonthefollowingformula:

    f(n)=0ifn=0f(n)=1ifn=1f(n)=f(n1)+f(n2)ifn>1

    Pleasewriteaprogramtocomputethevalueoff(n)withagivenninputbyconsole.

    Example:Ifthefollowingnisgivenasinputtotheprogram:

    7

    Then,theoutputoftheprogramshouldbe:

    13

    Incaseofinputdatabeingsuppliedtothequestion,itshouldbeassumedtobeaconsoleinput.

    Hints:WecandefinerecursivefunctioninPython.

    Solution:

    deff(n):ifn==0:return0

    elifn==1:return1else:returnf(n1)+f(n2)

    n=int(raw_input())printf(n)

    ##

    ##

    Question:

    TheFibonacciSequenceiscomputedbasedonthefollowingformula:

    f(n)=0ifn=0f(n)=1ifn=1f(n)=f(n1)+f(n2)ifn>1

    PleasewriteaprogramusinglistcomprehensiontoprinttheFibonacciSequenceincommaseparatedformwithagivenninputbyconsole.

    Example:Ifthefollowingnisgivenasinputtotheprogram:

    7

    Then,theoutputoftheprogramshouldbe:

    0,1,1,2,3,5,8,13

    Hints:WecandefinerecursivefunctioninPython.Uselistcomprehensiontogeneratealistfromanexistinglist.

  • 166816691670167116721673167416751676167716781679168016811682

    1683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713

    1714171517161717171817191720172117221723172417251726172717281729173017311732

    17331734173517361737173817391740

    Usestring.join()tojoinalistofstrings.

    Incaseofinputdatabeingsuppliedtothequestion,itshouldbeassumedtobeaconsoleinput.

    Solution:

    deff(n):ifn==0:return0elifn==1:return1else:returnf(n1)+f(n2)

    n=int(raw_input())values=[str(f(x))forxinrange(0,n+1)]print",".join(values)

    ##

    Question:

    Pleasewriteaprogramusinggeneratortoprinttheevennumbersbetween0andnincommaseparatedformwhilenisinputbyconsole.

    Example:Ifthefollowingnisgivenasinputtotheprogram:

    10

    Then,theoutputoftheprogramshouldbe:

    0,2,4,6,8,10

    Hints:Useyieldtoproducethenextvalueingenerator.

    Incaseofinputdatabeingsuppliedtothequestion,itshouldbeassumedtobeaconsoleinput.

    Solution:

    defEvenGenerator(n):i=0whilei

  • 174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764

    176517661767176817691770177117721773177417751776177717781779178017811782

    17831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814

    Solution:

    defNumGenerator(n):foriinrange(n+1):ifi%5==0andi%7==0:yieldi

    n=int(raw_input())values=[]foriinNumGenerator(n):values.append(str(i))

    print",".join(values)

    ##

    Question:

    Pleasewriteassertstatementstoverifythateverynumberinthelist[2,4,6,8]iseven.

    Hints:Use"assertexpression"tomakeassertion.

    Solution:

    li=[2,4,6,8]foriinli:asserti%2==0

    ##Question:

    Pleasewriteaprogramwhichacceptsbasicmathematicexpressionfromconsoleandprinttheevaluationresult.

    Example:

    Ifthefollowingstringisgivenasinputtotheprogram:

    35+3

    Then,theoutputoftheprogramshouldbe:

    38

    Hints:Useeval()toevaluateanexpression.

    Solution:

    expression=raw_input()printeval(expression)

    ##Question:

    Pleasewriteabinarysearchfunctionwhichsearchesaniteminasortedlist.Thefunctionshouldreturntheindexofelementtobesearchedinthelist.

    Hints:Useif/eliftodealwithconditions.

    Solution:

    importmathdefbin_search(li,element):

  • 1815

    18161817181818191820182118221823182418251826182718281829183018311832

    1833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866

    1867186818691870187118721873187418751876187718781879188018811882

    18831884188518861887

    bottom=0

    top=len(li)1index=1whiletop>=bottomandindex==1:mid=int(math.floor((top+bottom)/2.0))ifli[mid]==element:index=midelifli[mid]>element:top=mid1else:bottom=mid+1

    returnindex

    li=[2,5,7,9,11,17,222]printbin_search(li,11)printbin_search(li,12)

    ##Question:

    Pleasewriteabinarysearchfunctionwhichsearchesaniteminasortedlist.Thefunctionshouldreturntheindexofelementtobesearchedinthelist.

    Hints:Useif/eliftodealwithconditions.

    Solution:

    importmathdefbin_search(li,element):bottom=0top=len(li)1index=1whiletop>=bottomandindex==1:mid=int(math.floor((top+bottom)/2.0))ifli[mid]==element:index=midelifli[mid]>element:top=mid1else:bottom=mid+1

    returnindex

    li=[2,5,7,9,11,17,222]printbin_search(li,11)printbin_search(li,12)

    ##Question:

    Pleasegeneratearandomfloatwherethevalueisbetween10and100usingPythonmathmodule.

    Hints:Userandom.random()togeneratearandomfloatin[0,1].

    Solution:

    importrandomprintrandom.random()*100

    ##

  • 188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917

    191819191920192119221923192419251926192719281929193019311932

    19331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961

    Question:

    Pleasegeneratearandomfloatwherethevalueisbetween5and95usingPythonmathmodule.

    Hints:Userandom.random()togeneratearandomfloatin[0,1].

    Solution:

    importrandomprintrandom.random()*1005

    ##Question:

    Pleasewriteaprogramtooutputarandomevennumberbetween0and10inclusiveusingrandommoduleandlistcomprehension.

    Hints:Userandom.choice()toarandomelementfromalist.

    Solution:

    importrandom

    printrandom.choice([iforiinrange(11)ifi%2==0])

    ##Question:

    Pleasewriteaprogramtooutputarandomnumber,whichisdivisibleby5and7,between0and10inclusiveusingrandommoduleandlistcomprehension.

    Hints:Userandom.choice()toarandomelementfromalist.

    Solution:

    importrandomprintrandom.choice([iforiinrange(201)ifi%5==0andi%7==0])

    ##

    Question:

    Pleasewriteaprogramtogeneratealistwith5randomnumbersbetween100and200inclusive.

    Hints:Userandom.sample()togeneratealistofrandomvalues.

    Solution:

    importrandomprintrandom.sample(range(100),5)

    ##Question:

    Pleasewriteaprogramtorandomlygeneratealistwith5evennumbersbetween100and200inclusive.

  • 1962196319641965196619671968

    19691970197119721973197419751976197719781979198019811982

    1983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019

    2020202120222023202420252026202720282029203020312032

    20332034

    Hints:Userandom.sample()togeneratealistofrandomvalues.

    Solution:

    importrandomprintrandom.sample([iforiinrange(100,201)ifi%2==0],5)

    ##Question:

    Pleasewriteaprogramtorandomlygeneratealistwith5numbers,whicharedivisibleby5and7,between1and1000inclusive.

    Hints:Userandom.sample()togeneratealistofrandomvalues.

    Solution:

    importrandomprintrandom.sample([iforiinrange(1,1001)ifi%5==0andi%7==0],5)

    ##

    Question:

    Pleasewriteaprogramtorandomlyprintaintegernumberbetween7and15inclusive.

    Hints:Userandom.randrange()toarandomintegerinagivenrange.

    Solution:

    importrandomprintrandom.randrange(7,16)

    ##

    Question:

    Pleasewriteaprogramtocompressanddecompressthestring"helloworld!helloworld!helloworld!helloworld!".

    Hints:Usezlib.compress()andzlib.decompress()tocompressanddecompressastring.

    Solution:

    importzlibs='helloworld!helloworld!helloworld!helloworld!'t=zlib.compress(s)printtprintzlib.decompress(t)

    ##Question:

    Pleasewriteaprogramtoprinttherunningtimeofexecutionof"1+1"for100times.

    Hints:Usetimeit()functiontomeasuretherunningtime.

  • 203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070

    207120722073207420752076207720782079208020812082

    20832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108

    Solution:

    fromtimeitimportTimert=Timer("foriinrange(100):1+1")printt.timeit()

    ##Question:

    Pleasewriteaprogramtoshuffleandprintthelist[3,6,7,8].

    Hints:Useshuffle()functiontoshufflealist.

    Solution:

    fromrandomimportshuffleli=[3,6,7,8]shuffle(li)printli

    ##Question:

    Pleasewriteaprogramtoshuffleandprintthelist[3,6,7,8].

    Hints:Useshuffle()functiontoshufflealist.

    Solution:

    fromrandomimportshuffleli=[3,6,7,8]shuffle(li)printli

    ##Question:

    Pleasewriteaprogramtogenerateallsentenceswheresubjectisin["I","You"]andverbisin["Play","Love"]andtheobjectisin["Hockey","Football"].

    Hints:Uselist[index]notationtogetaelementfromalist.

    Solution:

    subjects=["I","You"]verbs=["Play","Love"]objects=["Hockey","Football"]foriinrange(len(subjects)):forjinrange(len(verbs)):forkinrange(len(objects)):sentence="%s%s%s."%(subjects[i],verbs[j],objects[k])printsentence

    ##Pleasewriteaprogramtoprintthelistafterremovingdeleteevennumbersin[5,6,77,45,22,12,24].

    Hints:Uselistcomprehensiontodeleteabunchofelementfromalist.

    Solution:

    li=[5,6,77,45,22,12,24]li=[xforxinliifx%2!=0]printli

  • 2109211021112112211321142115211621172118211921202121

    21222123212421252126212721282129213021312132

    2133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172

    217321742175217621772178217921802181

    ##Question:

    Byusinglistcomprehension,pleasewriteaprogramtoprintthelistafterremovingdeletenumberswhicharedivisibleby5and7in[12,24,35,70,88,120,155].

    Hints:Uselistcomprehensiontodeleteabunchofelementfromalist.

    Solution:

    li=[12,24,35,70,88,120,155]li=[xforxinliifx%5!=0andx%7!=0]

    printli

    ##Question:

    Byusinglistcomprehension,pleasewriteaprogramtoprintthelistafterremovingthe0th,2nd,4th,6thnumbersin[12,24,35,70,88,120,155].

    Hints:Uselistcomprehensiontodeleteabunchofelementfromalist.Useenumerate()toget(index,value)tuple.

    Solution:

    li=[12,24,35,70,88,120,155]li=[xfor(i,x)inenumerate(li)ifi%2!=0]printli

    ##

    Question:

    Byusinglistcomprehension,pleasewriteaprogramgeneratea3*5*83Darraywhoseeachelementis0.

    Hints:Uselistcomprehensiontomakeanarray.

    Solution:

    array=[[[0forcolinrange(8)]forcolinrange(5)]forrowinrange(3)]printarray

    ##Question:

    Byusinglistcomprehension,pleasewriteaprogramtoprintthelistafterremovingthe0th,4th,5thnumbersin[12,24,35,70,88,120,155].

    Hints:Uselistcomprehensiontodeleteabunchofelementfromalist.Useenumerate()toget(index,value)tuple.

    Solution:

    li=[12,24,35,70,88,120,155]li=[xfor(i,x)inenumerate(li)ifinotin(0,4,5)]printli

    ##

    Question:

    Byusinglistcomprehension,pleasewriteaprogramtoprintthelistafterremovingthevalue24in[12,24,35,24,88,120,155].

    Hints:Uselist'sremovemethodtodeleteavalue.

    Solution:

    li=[12,24,35,24,88,120,155]

  • 218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232

    22332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255

    li=[xforxinliifx!=24]printli

    ##Question:

    Withtwogivenlists[1,3,6,78,35,55]and[12,24,35,24,88,120,155],writeaprogramtomakealistwhoseelementsareintersectionoftheabovegivenlists.

    Hints:Useset()and"&="todosetintersectionoperation.

    Solution:

    set1=set([1,3,6,78,35,55])set2=set([12,24,35,24,88,120,155])set1&=set2li=list(set1)printli

    ##

    Withagivenlist[12,24,35,24,88,120,155,88,120,155],writeaprogramtoprintthislistafterremovingallduplicatevalueswithoriginalorderreserved.

    Hints:Useset()tostoreanumberofvalueswithoutduplicate.

    Solution:

    defremoveDuplicate(li):newli=[]seen=set()foriteminli:ifitemnotinseen:seen.add(item)newli.append(item)

    returnnewli

    li=[12,24,35,24,88,120,155,88,120,155]printremoveDuplicate(li)

    ##Question:

    DefineaclassPersonanditstwochildclasses:MaleandFemale.Allclasseshaveamethod"getGender"whichcanprint"Male"forMaleclassand"Female"forFemaleclass.

    Hints:UseSubclass(Parentclass)todefineachildclass.

    Solution:

    classPerson(object):defgetGender(self):return"Unknown"

    classMale(Person):defgetGender(self):return"Male"

    classFemale(Person):defgetGender(self):return"Female"

    aMale=Male()aFemale=Female()printaMale.getGender()printaFemale.getGender()

    ##

  • 225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282

    228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324

    2325232623272328

    Question:

    Pleasewriteaprogramwhichcountandprintthenumbersofeachcharacterinastringinputbyconsole.

    Example:Ifthefollowingstringisgivenasinputtotheprogram:

    abcdefgabc

    Then,theoutputoftheprogramshouldbe:

    a,2c,2b,2e,1d,1g,1f,1

    Hints:Usedicttostorekey/valuepairs.Usedict.get()methodtolookupakeywithdefaultvalue.

    Solution:

    dic={}s=raw_input()

    forsins:dic[s]=dic.get(s,0)+1print'\n'.join(['%s,%s'%(k,v)fork,vindic.items()])

    ##

    Question:

    Pleasewriteaprogramwhichacceptsastringfromconsoleandprintitinreverseorder.

    Example:Ifthefollowingstringisgivenasinputtotheprogram:

    risetovotesir

    Then,theoutputoftheprogramshouldbe:

    risetovotesir

    Hints:Uselist[::1]toiteratealistinareverseorder.

    Solution:

    s=raw_input()s=s[::1]prints

    ##

    Question:

    Pleasewriteaprogramwhichacceptsastringfromconsoleandprintthecharactersthathaveevenindexes.

    Example:Ifthefollowingstringisgivenasinputtotheprogram:

    H1e2l3l4o5w6o7r8l9d

    Then,theoutputoftheprogramshouldbe:

    Helloworld

    Hints:Uselist[::2]toiteratealistbystep2.

  • 23292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375

    2376

    Solution:

    s=raw_input()s=s[::2]prints##

    Question:

    Pleasewriteaprogramwhichprintsallpermutationsof[1,2,3]

    Hints:Useitertools.permutations()togetpermutationsoflist.

    Solution:

    importitertoolsprintlist(itertools.permutations([1,2,3]))

    ##Question:

    WriteaprogramtosolveaclassicancientChinesepuzzle:Wecount35headsand94legsamongthechickensandrabbitsinafarm.Howmanyrabbitsandhowmanychickensdowehave?

    Hint:Useforlooptoiterateallpossiblesolutions.

    Solution:

    defsolve(numheads,numlegs):ns='Nosolutions!'foriinrange(numheads+1):j=numheadsiif2*i+4*j==numlegs:returni,jreturnns,ns

    numheads=35numlegs=94solutions=solve(numheads,numlegs)printsolutions

    ##

    Status API Training Shop Blog About2015GitHub,Inc. Terms Privacy Security Contact