python-programming-exercises_100+ python challenging programming exercises

Download Python-programming-exercises_100+ Python challenging programming exercises

Post on 05-Oct-2015

103 views

Category:

Documents

7 download

Embed Size (px)

DESCRIPTION

100+ python questions.

TRANSCRIPT

  • 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"]+=