Python-Programming-Exercises - 100+ Python Challenging Programming Exercises
Python-Programming-Exercises - 100+ Python Challenging Programming Exercises
Search
Explore
Features
Enterprise
Blog
zhiwehu / Pythonprogrammingexercises
Signup
Star
branch:master
55
Fork
xinlincaoonJun21,2012addedmorequestions
1contributor
2377lines(1585sloc) 51.343kb
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Raw
Blame
100+Pythonchallengingprogrammingexercises
History
1.
Leveldescription
Level Description
Level1BeginnermeanssomeonewhohasjustgonethroughanintroductoryPythoncourse.Hecansolvesomeproblemswith1or2Pythonclassesorfunct
Level2IntermediatemeanssomeonewhohasjustlearnedPython,butalreadyhasarelativelystrongprogrammingbackgroundfrombefore.Heshouldbea
Level3Advanced.HeshouldusePythontosolvemorecomplexproblemusingmorerichlibrariesfunctionsanddatastructuresandalgorithms.Heissup
2.
Problemtemplate
##
Question
Hints
Solution
3.
Questions
##
Question1
Level1
Question:
Writeaprogramwhichwillfindallsuchnumberswhicharedivisibleby7butarenotamultipleof5,
between2000and3200(bothincluded).
Thenumbersobtainedshouldbeprintedinacommaseparatedsequenceonasingleline.
27
28
Hints:
Consideruserange(#begin,#end)method
29
30
31
32
Solution:
l=[]
foriinrange(2000,3201):
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
76
Pythonprogrammingexercises/100+Pythonchallengingprogrammingexercises.txt
1
2
3
4
Signin
if(i%7==0)and(i%5!=0):
l.append(str(i))
print','.join(l)
##
##
Question2
Level1
Question:
Writeaprogramwhichcancomputethefactorialofagivennumbers.
Theresultsshouldbeprintedinacommaseparatedsequenceonasingleline.
Supposethefollowinginputissuppliedtotheprogram:
8
Then,theoutputshouldbe:
40320
Hints:
Incaseofinputdatabeingsuppliedtothequestion,itshouldbeassumedtobeaconsoleinput.
Solution:
deffact(x):
56
ifx==0:
57
return1
58
returnx*fact(x1)
59
60
x=int(raw_input())
61
62
63
printfact(x)
##
64
##
65
Question3
Level1
66
67
68
69
70
Question:
Withagivenintegralnumbern,writeaprogramtogenerateadictionarythatcontains(i,i*i)suchthatisanintegralnumberbetween1andn(both
Supposethefollowinginputissuppliedtotheprogram:
71
72
Then,theoutputshouldbe:
{1:1,2:4,3:9,4:16,5:25,6:36,7:49,8:64}
73
74
75
76
77
Hints:
Incaseofinputdatabeingsuppliedtothequestion,itshouldbeassumedtobeaconsoleinput.
Considerusedict()
78
79
80
81
Solution:
n=int(raw_input())
d=dict()
82
foriinrange(1,n+1):
83
d[i]=i*i
84
85
86
87
printd
##
88
89
90
##
Question4
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
Level1
Question:
Writeaprogramwhichacceptsasequenceofcommaseparatednumbersfromconsoleandgeneratealistandatuplewhichcontainseverynumber.
Supposethefollowinginputissuppliedtotheprogram:
34,67,55,33,12,98
Then,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)
printl
printt
##
##
Question5
Level1
Question:
Defineaclasswhichhasatleasttwomethods:
getString:togetastringfromconsoleinput
printString:toprintthestringinuppercase.
Alsopleaseincludesimpletestfunctiontotesttheclassmethods.
122
123
Hints:
Use__init__methodtoconstructsomeparameters
124
125
126
Solution:
127
128
classInputOutString(object):
def__init__(self):
self.s=""
129
130
131
defgetString(self):
self.s=raw_input()
132
133
134
135
136
137
138
139
140
defprintString(self):
printself.s.upper()
strObj=InputOutString()
strObj.getString()
strObj.printString()
##
141
142
##
Question6
143
144
145
Level2
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
Question:
Writeaprogramthatcalculatesandprintsthevalueaccordingtothegivenformula:
Q=Squarerootof[(2*C*D)/H]
FollowingarethefixedvaluesofCandH:
Cis50.His30.
Disthevariablewhosevaluesshouldbeinputtoyourprograminacommaseparatedsequence.
Example
Letusassumethefollowingcommaseparatedinputsequenceisgiventotheprogram:
100,150,180
Theoutputoftheprogramshouldbe:
18,22,24
Hints:
Iftheoutputreceivedisindecimalform,itshouldberoundedofftoitsnearestvalue(forexample,iftheoutputreceivedis26.0,itshouldbepr
Incaseofinputdatabeingsuppliedtothequestion,itshouldbeassumedtobeaconsoleinput.
Solution:
#!/usr/bin/envpython
importmath
c=50
h=30
value=[]
items=[xforxinraw_input().split(',')]
fordinitems:
value.append(str(int(round(math.sqrt(2*c*float(d)/h)))))
171
172
173
print','.join(value)
##
174
175
176
##
Question7
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
Level2
Question:
Writeaprogramwhichtakes2digits,X,Yasinputandgeneratesa2dimensionalarray.Theelementvalueintheithrowandjthcolumnofthearray
Note:i=0,1..,X1;j=0,1,
Y1.
Example
Supposethefollowinginputsaregiventotheprogram:
3,5
Then,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
202
203
##
204
205
206
207
208
209
##
Question8
Level2
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
Question:
Writeaprogramthatacceptsacommaseparatedsequenceofwordsasinputandprintsthewordsinacommaseparatedsequenceaftersortingthemalphab
Supposethefollowinginputissuppliedtotheprogram:
without,hello,bag,world
Then,theoutputshouldbe:
bag,hello,without,world
Hints:
Incaseofinputdatabeingsuppliedtothequestion,itshouldbeassumedtobeaconsoleinput.
Solution:
items=[xforxinraw_input().split(',')]
items.sort()
print','.join(items)
##
##
Question9
Level2
Question
Writeaprogramthatacceptssequenceoflinesasinputandprintsthelinesaftermakingallcharactersinthesentencecapitalized.
Supposethefollowinginputissuppliedtotheprogram:
Helloworld
Practicemakesperfect
233
234
235
236
Then,theoutputshouldbe:
HELLOWORLD
PRACTICEMAKESPERFECT
237
238
239
240
Hints:
Incaseofinputdatabeingsuppliedtothequestion,itshouldbeassumedtobeaconsoleinput.
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
Solution:
lines=[]
whileTrue:
s=raw_input()
ifs:
lines.append(s.upper())
else:
break;
forsentenceinlines:
printsentence
##
##
Question10
Level2
Question:
Writeaprogramthatacceptsasequenceofwhitespaceseparatedwordsasinputandprintsthewordsafterremovingallduplicatewordsandsortingthe
Supposethefollowinginputissuppliedtotheprogram:
helloworldandpracticemakesperfectandhelloworldagain
Then,theoutputshouldbe:
againandhellomakesperfectpracticeworld
Hints:
Incaseofinputdatabeingsuppliedtothequestion,itshouldbeassumedtobeaconsoleinput.
Weusesetcontainertoremoveduplicateddataautomaticallyandthenusesorted()tosortthedata.
Solution:
s=raw_input()
words=[wordforwordins.split("")]
print"".join(sorted(list(set(words))))
##
##
Question11
276
277
278
279
280
281
282
Level2
Question:
Writeaprogramwhichacceptsasequenceofcommaseparated4digitbinarynumbersasitsinputandthencheckwhethertheyaredivisibleby5ornot.
Example:
0100,0011,1010,1001
Thentheoutputshouldbe:
283
284
285
286
1010
Notes:Assumethedataisinputbyconsole.
287
Incaseofinputdatabeingsuppliedtothequestion,itshouldbeassumedtobeaconsoleinput.
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
Hints:
Solution:
value=[]
items=[xforxinraw_input().split(',')]
forpinitems:
intp=int(p,2)
ifnotintp%5:
value.append(p)
print','.join(value)
##
##
Question12
Level2
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)
##
##
Question13
Level2
Question:
Writeaprogramthatacceptsasentenceandcalculatethenumberoflettersanddigits.
Supposethefollowinginputissuppliedtotheprogram:
helloworld!123
Then,theoutputshouldbe:
LETTERS10
DIGITS3
Hints:
Incaseofinputdatabeingsuppliedtothequestion,itshouldbeassumedtobeaconsoleinput.
Solution:
s=raw_input()
d={"DIGITS":0,"LETTERS":0}
forcins:
ifc.isdigit():
d["DIGITS"]+=1
elifc.isalpha():
d["LETTERS"]+=1
else:
pass
print"LETTERS",d["LETTERS"]
print"DIGITS",d["DIGITS"]
##
349
350
351
##
Question14
Level2
352
353
354
355
356
357
Question:
Writeaprogramthatacceptsasentenceandcalculatethenumberofuppercaselettersandlowercaseletters.
Supposethefollowinginputissuppliedtotheprogram:
Helloworld!
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
Then,theoutputshouldbe:
UPPERCASE1
LOWERCASE9
Hints:
Incaseofinputdatabeingsuppliedtothequestion,itshouldbeassumedtobeaconsoleinput.
Solution:
s=raw_input()
d={"UPPERCASE":0,"LOWERCASE":0}
forcins:
ifc.isupper():
d["UPPERCASE"]+=1
elifc.islower():
d["LOWERCASE"]+=1
else:
pass
print"UPPERCASE",d["UPPERCASE"]
print"LOWERCASE",d["LOWERCASE"]
##
##
Question15
380
381
382
Level2
383
384
385
386
387
Writeaprogramthatcomputesthevalueofa+aa+aaa+aaaawithagivendigitasthevalueofa.
Supposethefollowinginputissuppliedtotheprogram:
9
Then,theoutputshouldbe:
388
389
Question:
11106
Hints:
390
391
Incaseofinputdatabeingsuppliedtothequestion,itshouldbeassumedtobeaconsoleinput.
392
Solution:
393
394
a=raw_input()
n1=int("%s"%a)
395
396
n2=int("%s%s"%(a,a))
397
n3=int("%s%s%s"%(a,a,a))
n4=int("%s%s%s%s"%(a,a,a,a))
398
399
printn1+n2+n3+n4
##
400
401
##
402
Question16
403
404
Level2
405
406
Question:
Usealistcomprehensiontosquareeachoddnumberinalist.Thelistisinputbyasequenceofcommaseparatednumbers.
407
Supposethefollowinginputissuppliedtotheprogram:
408
409
1,2,3,4,5,6,7,8,9
Then,theoutputshouldbe:
410
411
1,3,5,7,9
412
413
Hints:
Incaseofinputdatabeingsuppliedtothequestion,itshouldbeassumedtobeaconsoleinput.
414
415
416
Solution:
values=raw_input()
417
418
numbers=[xforxinvalues.split(",")ifint(x)%2!=0]
print",".join(numbers)
419
##
420
421
Question17
422
Level2
423
424
425
Question:
Writeaprogramthatcomputesthenetamountofabankaccountbasedatransactionlogfromconsoleinput.Thetransactionlogformatisshownasfoll
426
D100
427
428
W200
429
430
DmeansdepositwhileWmeanswithdrawal.
Supposethefollowinginputissuppliedtotheprogram:
431
432
D300
433
434
W200
D100
435
Then,theoutputshouldbe:
436
437
500
438
439
Hints:
Incaseofinputdatabeingsuppliedtothequestion,itshouldbeassumedtobeaconsoleinput.
D300
440
441
442
Solution:
importsys
443
444
netAmount=0
whileTrue:
445
446
s=raw_input()
447
ifnots:
break
448
449
values=s.split("")
operation=values[0]
450
451
amount=int(values[1])
452
ifoperation=="D":
netAmount+=amount
453
454
elifoperation=="W":
netAmount=amount
455
456
else:
pass
457
printnetAmount
458
459
##
460
461
##
Question18
462
Level3
463
464
Question:
465
466
Awebsiterequirestheuserstoinputusernameandpasswordtoregister.Writeaprogramtocheckthevalidityofpasswordinputbyusers.
Followingarethecriteriaforcheckingthepassword:
467
468
1.Atleast1letterbetween[az]
469
2.Atleast1numberbetween[09]
1.Atleast1letterbetween[AZ]
470
471
3.Atleast1characterfrom[$#@]
4.Minimumlengthoftransactionpassword:6
472
473
5.Maximumlengthoftransactionpassword:12
Yourprogramshouldacceptasequenceofcommaseparatedpasswordsandwillcheckthemaccordingtotheabovecriteria.Passwordsthatmatchthecrite
474
Example
475
476
Ifthefollowingpasswordsaregivenasinputtotheprogram:
ABd1234@1,aF1#,2w3E*,2We3345
477
478
Then,theoutputoftheprogramshouldbe:
ABd1234@1
479
480
481
Hints:
Incaseofinputdatabeingsuppliedtothequestion,itshouldbeassumedtobeaconsoleinput.
482
483
Solutions:
484
485
importre
value=[]
486
487
items=[xforxinraw_input().split(',')]
forpinitems:
488
iflen(p)<6orlen(p)>12:
489
490
continue
else:
491
pass
492
ifnotre.search("[az]",p):
493
494
continue
elifnotre.search("[09]",p):
495
continue
496
elifnotre.search("[AZ]",p):
497
498
continue
elifnotre.search("[$#@]",p):
499
500
continue
elifre.search("\s",p):
501
continue
502
503
else:
pass
504
505
value.append(p)
print",".join(value)
506
507
##
508
##
509
510
Question19
Level3
511
512
Question:
513
Youarerequiredtowriteaprogramtosortthe(name,age,height)tuplesbyascendingorderwherenameisstring,ageandheightarenumbers.Thetu
514
515
1:Sortbasedonname;
2:Thensortbasedonage;
516
517
3:Thensortbyscore.
Thepriorityisthatname>age>score.
518
Ifthefollowingtuplesaregivenasinputtotheprogram:
519
520
Tom,19,80
John,20,90
521
522
Jony,17,91
Jony,17,93
523
524
Json,21,85
525
Then,theoutputoftheprogramshouldbe:
[('John','20','90'),('Jony','17','91'),('Jony','17','93'),('Json','21','85'),('Tom','19','80')]
526
527
Hints:
528
529
Incaseofinputdatabeingsuppliedtothequestion,itshouldbeassumedtobeaconsoleinput.
Weuseitemgettertoenablemultiplesortkeys.
530
531
532
Solutions:
fromoperatorimportitemgetter,attrgetter
533
534
l=[]
535
whileTrue:
536
537
s=raw_input()
ifnots:
538
539
break
l.append(tuple(s.split(",")))
540
541
printsorted(l,key=itemgetter(0,1,2))
542
543
##
544
##
545
546
Question20
Level3
547
548
Question:
549
Defineaclasswithageneratorwhichcaniteratethenumbers,whicharedivisibleby7,betweenagivenrange0andn.
550
551
Hints:
552
553
Consideruseyield
554
Solution:
555
556
defputNumbers(n):
i=0
557
558
whilei<n:
j=i
559
560
i=i+1
561
ifj%7==0:
yieldj
562
563
foriinreverse(100):
564
565
printi
##
566
567
568
##
Question21
569
570
Level3
571
572
Question
Arobotmovesinaplanestartingfromtheoriginalpoint(0,0).TherobotcanmovetowardUP,DOWN,LEFTandRIGHTwithagivensteps.Thetraceofr
573
UP5
574
575
DOWN3
LEFT3
576
577
RIGHT2
578
579
Thenumbersafterthedirectionaresteps.Pleasewriteaprogramtocomputethedistancefromcurrentpositionafterasequenceofmovementandorigi
580
Example:
Ifthefollowingtuplesaregivenasinputtotheprogram:
581
582
UP5
DOWN3
583
584
LEFT3
RIGHT2
585
Then,theoutputoftheprogramshouldbe:
586
587
588
589
Hints:
Incaseofinputdatabeingsuppliedtothequestion,itshouldbeassumedtobeaconsoleinput.
590
591
592
Solution:
importmath
594
pos=[0,0]
whileTrue:
595
596
s=raw_input()
ifnots:
597
598
break
593
599
movement=s.split("")
direction=movement[0]
600
601
steps=int(movement[1])
ifdirection=="UP":
602
603
pos[0]+=steps
elifdirection=="DOWN":
604
pos[0]=steps
605
606
elifdirection=="LEFT":
pos[1]=steps
607
608
elifdirection=="RIGHT":
pos[1]+=steps
609
else:
610
611
pass
612
613
printint(round(math.sqrt(pos[1]**2+pos[0]**2)))
##
614
615
616
##
Question22
617
618
Level3
619
620
Question:
Writeaprogramtocomputethefrequencyofthewordsfromtheinput.Theoutputshouldoutputaftersortingthekeyalphanumerically.
621
Supposethefollowinginputissuppliedtotheprogram:
622
623
NewtoPythonorchoosingbetweenPython2andPython3?ReadPython2orPython3.
Then,theoutputshouldbe:
624
625
2:2
3.:1
626
3?:1
627
628
New:1
Python:5
629
630
Read:1
and:1
631
632
between:1
633
634
or:2
choosing:1
to:1
635
636
637
638
639
Hints
Incaseofinputdatabeingsuppliedtothequestion,itshouldbeassumedtobeaconsoleinput.
640
Solution:
freq={}#frequencyofwordsintext
641
642
line=raw_input()
forwordinline.split():
643
freq[word]=freq.get(word,0)+1
644
645
646
words=freq.keys()
words.sort()
647
648
649
forwinwords:
print"%s:%d"%(w,freq[w])
650
651
##
652
##
653
654
Question23
level1
655
656
Question:
657
Writeamethodwhichcancalculatesquarevalueofnumber
658
659
Hints:
660
661
Usingthe**operator
662
663
Solution:
664
defsquare(num):
returnnum**2
665
666
printsquare(2)
667
668
printsquare(3)
##
669
670
671
##
Question24
672
673
Level1
674
Question:
675
676
Pythonhasmanybuiltinfunctions,andifyoudonotknowhowtouseit,youcanreaddocumentonlineorfindsomebooks.ButPythonhasabuilt
PleasewriteaprogramtoprintsomePythonbuiltinfunctionsdocuments,suchasabs(),int(),raw_input()
677
678
Andadddocumentforyourownfunction
679
Hints:
680
681
Thebuiltindocumentmethodis__doc__
682
Solution:
683
printabs.__doc__
684
685
printint.__doc__
printraw_input.__doc__
686
687
defsquare(num):
688
'''Returnthesquarevalueoftheinputnumber.
689
690
Theinputnumbermustbeinteger.
691
692
'''
returnnum**2
693
694
printsquare(2)
695
printsquare.__doc__
696
697
##
698
699
##
700
Question25
Level1
701
702
Question:
703
704
Defineaclass,whichhaveaclassparameterandhaveasameinstanceparameter.
705
Hints:
706
707
Defineainstanceparameter,needadditin__init__method
Youcaninitaobjectwithconstructparameterorsetthevaluelater
708
709
Solution:
710
classPerson:
711
712
#Definetheclassparameter"name"
name="Person"
713
714
def__init__(self,name=None):
715
#self.nameistheinstanceparameter
716
self.name=name
717
718
jeffrey=Person("Jeffrey")
719
720
print"%snameis%s"%(Person.name,jeffrey.name)
721
nico=Person()
722
723
nico.name="Nico"
print"%snameis%s"%(Person.name,nico.name)
724
725
##
726
727
##
728
Question:
Defineafunctionwhichcancomputethesumoftwonumbers.
729
730
Hints:
731
732
Defineafunctionwithtwonumbersasarguments.Youcancomputethesuminthefunctionandreturnthevalue.
733
734
Solution
defSumFunction(number1,number2):
735
736
737
printSumFunction(1,2)
738
739
##
740
741
Question:
Defineafunctionthatcanconvertaintegerintoastringandprintitinconsole.
returnnumber1+number2
742
743
744
Hints:
745
Usestr()toconvertanumbertostring.
746
747
Solution
748
749
defprintValue(n):
printstr(n)
750
751
printValue(3)
752
753
754
##
755
756
Question:
Defineafunctionthatcanconvertaintegerintoastringandprintitinconsole.
757
758
Hints:
759
760
761
Usestr()toconvertanumbertostring.
762
763
Solution
764
defprintValue(n):
printstr(n)
765
766
printValue(3)
767
768
##
769
2.10
770
771
Question:
772
773
Defineafunctionthatcanreceivetwointegralnumbersinstringformandcomputetheirsumandthenprintitinconsole.
774
Hints:
775
776
Useint()toconvertastringtointeger.
777
778
Solution
779
780
defprintValue(s1,s2):
printint(s1)+int(s2)
781
782
printValue("3","4")#7
783
784
785
##
786
787
2.10
788
789
Question:
790
791
Defineafunctionthatcanaccepttwostringsasinputandconcatenatethemandthenprintitinconsole.
792
Hints:
793
794
Use+toconcatenatethestrings
795
796
Solution
797
defprintValue(s1,s2):
798
799
800
prints1+s2
printValue("3","4")#34
801
802
803
##
2.10
804
805
806
807
Question:
Defineafunctionthatcanaccepttwostringsasinputandprintthestringwithmaximumlengthinconsole.Iftwostringshavethesamelength,then
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
Hints:
Uselen()functiontogetthelengthofastring
Solution
defprintValue(s1,s2):
len1=len(s1)
len2=len(s2)
iflen1>len2:
prints1
eliflen2>len1:
prints2
else:
prints1
printValue("one","three")
##
2.10
833
834
835
Question:
836
837
838
Hints:
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
Defineafunctionthatcanacceptanintegernumberasinputandprintthe"Itisanevennumber"ifthenumberiseven,otherwiseprint"Itisanodd
Use%operatortocheckifanumberisevenorodd.
Solution
defcheckValue(n):
ifn%2==0:
print"Itisanevennumber"
else:
print"Itisanoddnumber"
checkValue(7)
##
2.10
854
855
856
Question:
857
858
859
860
Hints:
861
prints2
Defineafunctionwhichcanprintadictionarywherethekeysarenumbersbetween1and3(bothincluded)andthevaluesaresquareofkeys.
Usedict[key]=valuepatterntoputentryintoadictionary.
Use**operatortogetpowerofanumber.
862
863
864
865
866
867
868
869
870
871
872
873
Solution
defprintDict():
d=dict()
d[1]=1
d[2]=2**2
d[3]=3**2
printd
printDict()
874
875
876
877
878
879
##
2.10
880
881
882
Question:
Defineafunctionwhichcanprintadictionarywherethekeysarenumbersbetween1and20(bothincluded)andthevaluesaresquareofkeys.
883
884
885
886
Hints:
887
888
889
890
891
892
893
894
895
896
897
898
Usedict[key]=valuepatterntoputentryintoadictionary.
Use**operatortogetpowerofanumber.
Userange()forloops.
Solution
defprintDict():
d=dict()
foriinrange(1,21):
d[i]=i**2
printd
printDict()
899
900
901
902
##
903
904
905
Question:
Defineafunctionwhichcangenerateadictionarywherethekeysarenumbersbetween1and20(bothincluded)andthevaluesaresquareofkeys.Thef
906
907
908
909
Hints:
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
2.10
Usedict[key]=valuepatterntoputentryintoadictionary.
Use**operatortogetpowerofanumber.
Userange()forloops.
Usekeys()toiteratekeysinthedictionary.Alsowecanuseitem()togetkey/valuepairs.
Solution
defprintDict():
d=dict()
foriinrange(1,21):
d[i]=i**2
for(k,v)ind.items():
printv
printDict()
##
2.10
927
928
929
Question:
930
931
932
Hints:
933
934
Use**operatortogetpowerofanumber.
Userange()forloops.
Defineafunctionwhichcangenerateadictionarywherethekeysarenumbersbetween1and20(bothincluded)andthevaluesaresquareofkeys.Thef
Usedict[key]=valuepatterntoputentryintoadictionary.
935
936
937
938
939
940
941
942
943
944
945
Usekeys()toiteratekeysinthedictionary.Alsowecanuseitem()togetkey/valuepairs.
Solution
defprintDict():
d=dict()
foriinrange(1,21):
d[i]=i**2
forkind.keys():
printk
946
947
948
949
printDict()
950
2.10
951
952
953
Question:
Defineafunctionwhichcangenerateandprintalistwherethevaluesaresquareofnumbersbetween1and20(bothincluded).
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
##
Hints:
Use**operatortogetpowerofanumber.
Userange()forloops.
Uselist.append()toaddvaluesintoalist.
Solution
defprintList():
li=list()
foriinrange(1,21):
li.append(i**2)
printli
printList()
##
2.10
Question:
Defineafunctionwhichcangeneratealistwherethevaluesaresquareofnumbersbetween1and20(bothincluded).Thenthefunctionneedstoprint
Hints:
Use**operatortogetpowerofanumber.
Userange()forloops.
Uselist.append()toaddvaluesintoalist.
Use[n1:n2]toslicealist
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
Solution
defprintList():
li=list()
foriinrange(1,21):
li.append(i**2)
printli[:5]
printList()
##
2.10
998
999
1000
Question:
1001
1002
1003
Hints:
1004
1005
1006
1007
Defineafunctionwhichcangeneratealistwherethevaluesaresquareofnumbersbetween1and20(bothincluded).Thenthefunctionneedstoprint
Use**operatortogetpowerofanumber.
Userange()forloops.
Uselist.append()toaddvaluesintoalist.
Use[n1:n2]toslicealist
1008
1009
1010
1011
1012
1013
1014
1015
Solution
defprintList():
li=list()
foriinrange(1,21):
li.append(i**2)
printli[5:]
1016
1017
1018
printList()
1019
1020
1021
##
2.10
1022
1023
1024
1025
Question:
Defineafunctionwhichcangeneratealistwherethevaluesaresquareofnumbersbetween1and20(bothincluded).Thenthefunctionneedstoprint
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
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:
1051
Use**operatortogetpowerofanumber.
1052
1053
1054
Userange()forloops.
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
Uselist.append()toaddvaluesintoalist.
Usetuple()togetatuplefromalist.
Solution
defprintTuple():
li=list()
foriinrange(1,21):
li.append(i**2)
printtuple(li)
printTuple()
1065
1066
1067
1068
##
2.10
1069
1070
1071
Question:
Withagiventuple(1,2,3,4,5,6,7,8,9,10),writeaprogramtoprintthefirsthalfvaluesinonelineandthelasthalfvaluesinoneline.
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
Hints:
Use[n1:n2]notationtogetaslicefromatuple.
Solution
tp=(1,2,3,4,5,6,7,8,9,10)
tp1=tp[:5]
tp2=tp[5:]
printtp1
1082
printtp2
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
##
2.10
Question:
Writeaprogramtogenerateandprintanothertuplewhosevaluesareevennumbersinthegiventuple(1,2,3,4,5,6,7,8,9,10).
Hints:
Use"for"toiteratethetuple
Usetuple()togenerateatuplefromalist.
Solution
tp=(1,2,3,4,5,6,7,8,9,10)
li=list()
foriintp:
iftp[i]%2==0:
li.append(tp[i])
1102
1103
1104
tp2=tuple(li)
printtp2
1105
1106
1107
1108
1109
1110
##
2.14
1111
1112
1113
1114
Question:
Writeaprogramwhichacceptsastringasinputtoprint"Yes"ifthestringis"yes"or"YES"or"Yes",otherwiseprint"No".
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
Hints:
Useifstatementtojudgecondition.
Solution
s=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].
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
Hints:
Usefilter()tofiltersomeelementsinalist.
Uselambdatodefineanonymousfunctions.
Solution
li=[1,2,3,4,5,6,7,8,9,10]
evenNumbers=filter(lambdax:x%2==0,li)
printevenNumbers
1144
1145
1146
##
1147
1148
1149
Question:
Writeaprogramwhichcanmap()tomakealistwhoseelementsaresquareofelementsin[1,2,3,4,5,6,7,8,9,10].
1150
1151
1152
1153
Hints:
1154
3.4
Usemap()togeneratealist.
Uselambdatodefineanonymousfunctions.
1155
1156
1157
1158
Solution
li=[1,2,3,4,5,6,7,8,9,10]
squaredNumbers=map(lambdax:x**2,li)
printsquaredNumbers
1159
1160
1161
##
3.5
1162
1163
1164
Question:
Writeaprogramwhichcanmap()andfilter()tomakealistwhoseelementsaresquareofevennumberin[1,2,3,4,5,6,7,8,9,10].
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
Hints:
Usemap()togeneratealist.
Usefilter()tofilterelementsofalist.
Uselambdatodefineanonymousfunctions.
Solution
li=[1,2,3,4,5,6,7,8,9,10]
evenNumbers=map(lambdax:x**2,filter(lambdax:x%2==0,li))
printevenNumbers
1176
1177
1178
1179
1180
1181
##
3.5
1182
1183
1184
1185
Question:
1186
1187
1188
Hints:
1189
1190
1191
1192
1193
1194
1195
Writeaprogramwhichcanfilter()tomakealistwhoseelementsareevennumberbetween1and20(bothincluded).
Usefilter()tofilterelementsofalist.
Uselambdatodefineanonymousfunctions.
Solution
evenNumbers=filter(lambdax:x%2==0,range(1,21))
printevenNumbers
1196
1197
1198
##
1199
1200
1201
1202
Question:
Writeaprogramwhichcanmap()tomakealistwhoseelementsaresquareofnumbersbetween1and20(bothincluded).
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
3.5
Hints:
Usemap()togeneratealist.
Uselambdatodefineanonymousfunctions.
Solution
squaredNumbers=map(lambdax:x**2,range(1,21))
printsquaredNumbers
##
7.2
Question:
DefineaclassnamedAmericanwhichhasastaticmethodcalledprintNationality.
Hints:
Use@staticmethoddecoratortodefineclassstaticmethod.
Solution
classAmerican(object):
@staticmethod
defprintNationality():
print"America"
1229
1230
1231
1232
anAmerican=American()
anAmerican.printNationality()
American.printNationality()
1233
1234
1235
1236
1237
1238
1239
1240
##
1241
1242
1243
Question:
1244
1245
1246
1247
Hints:
1248
1249
1250
Solution:
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
7.2
DefineaclassnamedAmericananditssubclassNewYorker.
UseclassSubclass(ParentClass)todefineasubclass.
classAmerican(object):
pass
classNewYorker(American):
pass
anAmerican=American()
aNewYorker=NewYorker()
printanAmerican
printaNewYorker
1261
1262
1263
1264
##
1265
1266
1267
7.2
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
Question:
DefineaclassnamedCirclewhichcanbeconstructedbyaradius.TheCircleclasshasamethodwhichcancomputethearea.
Hints:
UsedefmethodName(self)todefineamethod.
Solution:
1278
1279
1280
1281
classCircle(object):
def__init__(self,r):
1282
defarea(self):
1283
1284
1285
returnself.radius**2*3.14
1286
1287
1288
self.radius=r
aCircle=Circle(2)
printaCircle.area()
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
##
7.2
DefineaclassnamedRectanglewhichcanbeconstructedbyalengthandwidth.TheRectangleclasshasamethodwhichcancomputethearea.
Hints:
UsedefmethodName(self)todefineamethod.
1302
1303
1304
Solution:
1305
1306
classRectangle(object):
1307
1308
1309
self.length=l
1310
1311
1312
defarea(self):
returnself.length*self.width
1313
1314
1315
1316
aRectangle=Rectangle(2,10)
printaRectangle.area()
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
def__init__(self,l,w):
self.width=w
##
7.2
DefineaclassnamedShapeanditssubclassSquare.TheSquareclasshasaninitfunctionwhichtakesalengthasargument.Bothclasseshaveaareaf
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
1343
1344
1345
defarea(self):
1346
1347
1348
1349
aSquare=Square(3)
printaSquare.area()
returnself.length*self.length
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
##
PleaseraiseaRuntimeErrorexception.
Hints:
1363
1364
1365
1366
Useraise()toraiseanexception.
1367
1368
1369
raiseRuntimeError('somethingwrong')
1370
1371
1372
1373
1374
1375
Solution:
##
Writeafunctiontocompute5/0andusetry/excepttocatchtheexceptions.
Hints:
1376
1377
1378
1379
1380
1381
Usetry/excepttocatchexceptions.
Solution:
defthrows():
return5/0
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
try:
throws()
exceptZeroDivisionError:
print"divisionbyzero!"
exceptException,err:
print'Caughtanexception'
finally:
print'Infinallyblockforcleanup'
1393
1394
1395
##
1396
1397
1398
Hints:
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
Defineacustomexceptionclasswhichtakesastringmessageasattribute.
Todefineacustomexception,weneedtodefineaclassinheritedfromException.
Solution:
classMyError(Exception):
"""Myownexceptionclass
Attributes:
msgexplanationoftheerror
"""
def__init__(self,msg):
self.msg=msg
error=MyError("somethingwrong")
1414
1415
1416
##
1417
1418
1419
Assumingthatwehavesomeemailaddressesinthe"username@companyname.com"format,pleasewriteprogramtoprinttheusernameofagivenemailaddr
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
Question:
Example:
Ifthefollowingemailaddressisgivenasinputtotheprogram:
john@google.com
Then,theoutputoftheprogramshouldbe:
john
Incaseofinputdatabeingsuppliedtothequestion,itshouldbeassumedtobeaconsoleinput.
Hints:
Use\wtomatchletters.
Solution:
importre
emailAddress=raw_input()
pat2="(\w+)@((\w+\.)+(com))"
r2=re.match(pat2,emailAddress)
printr2.group(1)
##
Question:
Assumingthatwehavesomeemailaddressesinthe"username@companyname.com"format,pleasewriteprogramtoprintthecompanynameofagivenemaila
Example:
Ifthefollowingemailaddressisgivenasinputtotheprogram:
1449
1450
1451
1452
1453
1454
john@google.com
Then,theoutputoftheprogramshouldbe:
google
1455
1456
1457
Incaseofinputdatabeingsuppliedtothequestion,itshouldbeassumedtobeaconsoleinput.
1458
Hints:
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
Use\wtomatchletters.
Solution:
importre
emailAddress=raw_input()
pat2="(\w+)@(\w+)\.(com)"
r2=re.match(pat2,emailAddress)
printr2.group(2)
##
Question:
Writeaprogramwhichacceptsasequenceofwordsseparatedbywhitespaceasinputtoprintthewordscomposedofdigitsonly.
1477
1478
1479
Example:
Ifthefollowingwordsisgivenasinputtotheprogram:
1480
1481
1482
2catsand3dogs.
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
Then,theoutputoftheprogramshouldbe:
['2','3']
Incaseofinputdatabeingsuppliedtothequestion,itshouldbeassumedtobeaconsoleinput.
Hints:
Usere.findall()tofindallsubstringusingregex.
Solution:
importre
s=raw_input()
printre.findall("\d+",s)
##
Question:
Printaunicodestring"helloworld".
Hints:
Useu'strings'formattodefineunicodestring.
Solution:
1509
1510
1511
1512
unicodeString=u"helloworld!"
1513
1514
1515
1516
##
WriteaprogramtoreadanASCIIstringandtoconvertittoaunicodestringencodedbyutf8.
1517
1518
1519
1520
1521
printunicodeString
Hints:
Useunicode()functiontoconvert.
Solution:
1522
1523
1524
1525
1526
1527
1528
1529
1530
s=raw_input()
u=unicode(s,"utf8")
printu
##
Question:
WriteaspecialcommenttoindicateaPythonsourcecodefileisinunicode.
1531
1532
Hints:
1533
Solution:
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
#*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:
1558
1559
1560
n=int(raw_input())
sum=0.0
1561
1562
sum+=float(float(i)/(i+1))
printsum
1563
1564
1565
1566
##
Question:
1567
1568
1569
foriinrange(1,n+1):
Writeaprogramtocompute:
1570
1571
1572
f(n)=f(n1)+100whenn>0
andf(0)=1
1573
1574
1575
1576
withagivenninputbyconsole(n>0).
1577
1578
1579
1580
1581
1582
1583
1584
1585
Example:
Ifthefollowingnisgivenasinputtotheprogram:
5
Then,theoutputoftheprogramshouldbe:
500
Incaseofinputdatabeingsuppliedtothequestion,itshouldbeassumedtobeaconsoleinput.
1586
1587
1588
Hints:
1589
1590
1591
1592
Solution:
1593
1594
WecandefinerecursivefunctioninPython.
deff(n):
ifn==0:
return0
else:
returnf(n1)+100
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
n=int(raw_input())
printf(n)
##
Question:
TheFibonacciSequenceiscomputedbasedonthefollowingformula:
f(n)=0ifn=0
f(n)=1ifn=1
f(n)=f(n1)+f(n2)ifn>1
Pleasewriteaprogramtocomputethevalueoff(n)withagivenninputbyconsole.
Example:
Ifthefollowingnisgivenasinputtotheprogram:
7
1619
1620
1621
1622
1623
1624
Then,theoutputoftheprogramshouldbe:
1625
1626
1627
1628
1629
1630
1631
Hints:
WecandefinerecursivefunctioninPython.
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
13
Incaseofinputdatabeingsuppliedtothequestion,itshouldbeassumedtobeaconsoleinput.
Solution:
deff(n):
ifn==0:return0
elifn==1:return1
else:returnf(n1)+f(n2)
n=int(raw_input())
printf(n)
##
##
Question:
1646
1647
1648
1649
1650
1651
1652
TheFibonacciSequenceiscomputedbasedonthefollowingformula:
1653
1654
1655
1656
1657
1658
1659
PleasewriteaprogramusinglistcomprehensiontoprinttheFibonacciSequenceincommaseparatedformwithagivenninputbyconsole.
1660
1661
1662
Then,theoutputoftheprogramshouldbe:
1663
1664
1665
1666
1667
f(n)=0ifn=0
f(n)=1ifn=1
f(n)=f(n1)+f(n2)ifn>1
Example:
Ifthefollowingnisgivenasinputtotheprogram:
7
0,1,1,2,3,5,8,13
Hints:
WecandefinerecursivefunctioninPython.
Uselistcomprehensiontogeneratealistfromanexistinglist.
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
Usestring.join()tojoinalistofstrings.
Incaseofinputdatabeingsuppliedtothequestion,itshouldbeassumedtobeaconsoleinput.
Solution:
deff(n):
ifn==0:return0
elifn==1:return1
else:returnf(n1)+f(n2)
n=int(raw_input())
values=[str(f(x))forxinrange(0,n+1)]
print",".join(values)
##
Question:
Pleasewriteaprogramusinggeneratortoprinttheevennumbersbetween0andnincommaseparatedformwhilenisinputbyconsole.
1690
1691
1692
1693
1694
1695
1696
Example:
Ifthefollowingnisgivenasinputtotheprogram:
1697
1698
1699
1700
1701
1702
1703
0,2,4,6,8,10
1704
1705
1706
1707
1708
1709
1710
Solution:
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
10
Then,theoutputoftheprogramshouldbe:
Hints:
Useyieldtoproducethenextvalueingenerator.
Incaseofinputdatabeingsuppliedtothequestion,itshouldbeassumedtobeaconsoleinput.
defEvenGenerator(n):
i=0
whilei<=n:
ifi%2==0:
yieldi
i+=1
n=int(raw_input())
values=[]
foriinEvenGenerator(n):
values.append(str(i))
print",".join(values)
##
Question:
Pleasewriteaprogramusinggeneratortoprintthenumberswhichcanbedivisibleby5and7between0andnincommaseparatedformwhilenisinput
Example:
Ifthefollowingnisgivenasinputtotheprogram:
100
Then,theoutputoftheprogramshouldbe:
0,35,70
Hints:
Useyieldtoproducethenextvalueingenerator.
Incaseofinputdatabeingsuppliedtothequestion,itshouldbeassumedtobeaconsoleinput.
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
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.
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
Hints:
Use"assertexpression"tomakeassertion.
Solution:
li=[2,4,6,8]
foriinli:
asserti%2==0
##
Question:
Pleasewriteaprogramwhichacceptsbasicmathematicexpressionfromconsoleandprinttheevaluationresult.
1782
Example:
1783
1784
Ifthefollowingstringisgivenasinputtotheprogram:
1785
1786
1787
1788
1789
1790
1791
35+3
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
Then,theoutputoftheprogramshouldbe:
38
Hints:
Useeval()toevaluateanexpression.
Solution:
expression=raw_input()
printeval(expression)
##
Question:
Pleasewriteabinarysearchfunctionwhichsearchesaniteminasortedlist.Thefunctionshouldreturntheindexofelementtobesearchedinthel
Hints:
Useif/eliftodealwithconditions.
Solution:
importmath
defbin_search(li,element):
1815
bottom=0
1816
1817
top=len(li)1
index=1
whiletop>=bottomandindex==1:
mid=int(math.floor((top+bottom)/2.0))
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
ifli[mid]==element:
index=mid
elifli[mid]>element:
top=mid1
else:
bottom=mid+1
returnindex
li=[2,5,7,9,11,17,222]
printbin_search(li,11)
printbin_search(li,12)
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
##
Question:
Pleasewriteabinarysearchfunctionwhichsearchesaniteminasortedlist.Thefunctionshouldreturntheindexofelementtobesearchedinthel
Hints:
Useif/eliftodealwithconditions.
Solution:
importmath
defbin_search(li,element):
bottom=0
top=len(li)1
index=1
whiletop>=bottomandindex==1:
mid=int(math.floor((top+bottom)/2.0))
ifli[mid]==element:
index=mid
elifli[mid]>element:
top=mid1
else:
bottom=mid+1
returnindex
li=[2,5,7,9,11,17,222]
printbin_search(li,11)
printbin_search(li,12)
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
##
Question:
Pleasegeneratearandomfloatwherethevalueisbetween10and100usingPythonmathmodule.
Hints:
Userandom.random()togeneratearandomfloatin[0,1].
Solution:
importrandom
printrandom.random()*100
##
1888
1889
Question:
1890
1891
1892
1893
1894
1895
1896
Pleasegeneratearandomfloatwherethevalueisbetween5and95usingPythonmathmodule.
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
Hints:
Userandom.random()togeneratearandomfloatin[0,1].
Solution:
importrandom
printrandom.random()*1005
##
Question:
Pleasewriteaprogramtooutputarandomevennumberbetween0and10inclusiveusingrandommoduleandlistcomprehension.
Hints:
Userandom.choice()toarandomelementfromalist.
Solution:
1917
importrandom
1918
1919
printrandom.choice([iforiinrange(11)ifi%2==0])
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
##
Question:
Pleasewriteaprogramtooutputarandomnumber,whichisdivisibleby5and7,between0and10inclusiveusingrandommoduleandlistcomprehension
Hints:
Userandom.choice()toarandomelementfromalist.
Solution:
importrandom
printrandom.choice([iforiinrange(201)ifi%5==0andi%7==0])
##
Question:
Pleasewriteaprogramtogeneratealistwith5randomnumbersbetween100and200inclusive.
Hints:
Userandom.sample()togeneratealistofrandomvalues.
Solution:
importrandom
printrandom.sample(range(100),5)
##
Question:
Pleasewriteaprogramtorandomlygeneratealistwith5evennumbersbetween100and200inclusive.
1962
1963
1964
1965
1966
1967
1968
Hints:
Userandom.sample()togeneratealistofrandomvalues.
1969
1970
1971
1972
1973
importrandom
printrandom.sample([iforiinrange(100,201)ifi%2==0],5)
1974
1975
1976
1977
1978
1979
1980
1981
1982
Solution:
##
Question:
Pleasewriteaprogramtorandomlygeneratealistwith5numbers,whicharedivisibleby5and7,between1and1000inclusive.
Hints:
Userandom.sample()togeneratealistofrandomvalues.
1983
1984
1985
1986
1987
1988
1989
1990
Solution:
1991
1992
1993
1994
1995
1996
1997
Question:
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
importrandom
printrandom.sample([iforiinrange(1,1001)ifi%5==0andi%7==0],5)
##
Pleasewriteaprogramtorandomlyprintaintegernumberbetween7and15inclusive.
Hints:
Userandom.randrange()toarandomintegerinagivenrange.
Solution:
importrandom
printrandom.randrange(7,16)
##
Question:
Pleasewriteaprogramtocompressanddecompressthestring"helloworld!helloworld!helloworld!helloworld!".
Hints:
Usezlib.compress()andzlib.decompress()tocompressanddecompressastring.
2018
2019
Solution:
2020
2021
2022
2023
importzlib
s='helloworld!helloworld!helloworld!helloworld!'
t=zlib.compress(s)
printt
printzlib.decompress(t)
2024
2025
2026
2027
2028
2029
2030
##
Question:
Pleasewriteaprogramtoprinttherunningtimeofexecutionof"1+1"for100times.
2031
2032
2033
2034
Hints:
Usetimeit()functiontomeasuretherunningtime.
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
Solution:
fromtimeitimportTimer
t=Timer("foriinrange(100):1+1")
printt.timeit()
##
Question:
Pleasewriteaprogramtoshuffleandprintthelist[3,6,7,8].
Hints:
Useshuffle()functiontoshufflealist.
Solution:
fromrandomimportshuffle
li=[3,6,7,8]
shuffle(li)
printli
##
Question:
Pleasewriteaprogramtoshuffleandprintthelist[3,6,7,8].
Hints:
Useshuffle()functiontoshufflealist.
Solution:
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
fromrandomimportshuffle
li=[3,6,7,8]
shuffle(li)
printli
##
Question:
Pleasewriteaprogramtogenerateallsentenceswheresubjectisin["I","You"]andverbisin["Play","Love"]andtheobjectisin["Hockey","Foot
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
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
##
Question:
Byusinglistcomprehension,pleasewriteaprogramtoprintthelistafterremovingdeletenumberswhicharedivisibleby5and7in[12,24,35,70,88,
Hints:
Uselistcomprehensiontodeleteabunchofelementfromalist.
Solution:
li=[12,24,35,70,88,120,155]
li=[xforxinliifx%5!=0andx%7!=0]
2122
2123
2124
printli
2125
2126
2127
2128
2129
2130
2131
##
Question:
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
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:
2144
2145
2146
2147
2148
2149
2150
Byusinglistcomprehension,pleasewriteaprogramgeneratea3*5*83Darraywhoseeachelementis0.
2151
2152
2153
2154
2155
2156
2157
array=[[[0forcolinrange(8)]forcolinrange(5)]forrowinrange(3)]
printarray
2158
2159
2160
2161
2162
2163
2164
Hints:
Uselistcomprehensiontomakeanarray.
Solution:
##
Question:
Byusinglistcomprehension,pleasewriteaprogramtoprintthelistafterremovingthe0th,4th,5thnumbersin[12,24,35,70,88,120,155].
Hints:
Uselistcomprehensiontodeleteabunchofelementfromalist.
Useenumerate()toget(index,value)tuple.
Solution:
2165
2166
2167
2168
2169
2170
li=[12,24,35,70,88,120,155]
2171
2172
##
2173
2174
Question:
2175
2176
2177
2178
2179
2180
2181
Byusinglistcomprehension,pleasewriteaprogramtoprintthelistafterremovingthevalue24in[12,24,35,24,88,120,155].
li=[xfor(i,x)inenumerate(li)ifinotin(0,4,5)]
printli
Hints:
Uselist'sremovemethodtodeleteavalue.
Solution:
li=[12,24,35,24,88,120,155]
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
li=[xforxinliifx!=24]
printli
##
Question:
Withtwogivenlists[1,3,6,78,35,55]and[12,24,35,24,88,120,155],writeaprogramtomakealistwhoseelementsareintersectionoftheabovegiven
Hints:
Useset()and"&="todosetintersectionoperation.
Solution:
set1=set([1,3,6,78,35,55])
set2=set([12,24,35,24,88,120,155])
set1&=set2
li=list(set1)
printli
2203
2204
2205
2206
2207
2208
2209
##
2210
2211
2212
2213
2214
2215
Solution:
2216
2217
2218
2219
2220
2221
2222
Withagivenlist[12,24,35,24,88,120,155,88,120,155],writeaprogramtoprintthislistafterremovingallduplicatevalueswithoriginalorderrese
Hints:
Useset()tostoreanumberofvalueswithoutduplicate.
defremoveDuplicate(li):
newli=[]
seen=set()
foriteminli:
ifitemnotinseen:
seen.add(item)
newli.append(item)
returnnewli
2223
li=[12,24,35,24,88,120,155,88,120,155]
printremoveDuplicate(li)
2224
2225
2226
2227
##
Question:
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
DefineaclassPersonanditstwochildclasses:MaleandFemale.Allclasseshaveamethod"getGender"whichcanprint"Male"forMaleclassand"Fem
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()
##
2256
2257
2258
2259
2260
2261
2262
Question:
2263
2264
2265
2266
2267
2268
2269
abcdefgabc
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
Pleasewriteaprogramwhichcountandprintthenumbersofeachcharacterinastringinputbyconsole.
Example:
Ifthefollowingstringisgivenasinputtotheprogram:
Then,theoutputoftheprogramshouldbe:
a,2
c,2
b,2
e,1
d,1
g,1
f,1
Hints:
Usedicttostorekey/valuepairs.
Usedict.get()methodtolookupakeywithdefaultvalue.
Solution:
dic={}
s=raw_input()
forsins:
dic[s]=dic.get(s,0)+1
print'\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.
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
Solution:
s=raw_input()
s=s[::2]
prints
##
Question:
Pleasewriteaprogramwhichprintsallpermutationsof[1,2,3]
Hints:
Useitertools.permutations()togetpermutationsoflist.
Solution:
importitertools
printlist(itertools.permutations([1,2,3]))
##
Question:
WriteaprogramtosolveaclassicancientChinesepuzzle:
Wecount35headsand94legsamongthechickensandrabbitsinafarm.Howmanyrabbitsandhowmanychickensdowehave?
Hint:
Useforlooptoiterateallpossiblesolutions.
Solution:
defsolve(numheads,numlegs):
ns='Nosolutions!'
foriinrange(numheads+1):
j=numheadsi
if2*i+4*j==numlegs:
returni,j
returnns,ns
numheads=35
numlegs=94
solutions=solve(numheads,numlegs)
printsolutions
##
2376