Advertisement
dagger229

100+ Python challenging programming exercises

Jul 8th, 2015
636
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 52.47 KB | None | 0 0
  1. 100+ Python challenging programming exercises
  2.  
  3. 1Level description
  4. Level   Description
  5. Level 1 Beginner means someone who has just gone through an introductory Python course. He can solve some problems with 1 or 2 Python classes or functions. Normally, the answers could directly be found in the textbooks.
  6. Level 2 Intermediate means someone who has just learned Python, but already has a relatively strong programming background from before. He should be able to solve problems which may involve 3 or 3 Python classes or functions. The answers cannot be directly be found in the textbooks.
  7. Level 3 Advanced. He should use Python to solve more complex problem using more rich libraries functions and data structures and algorithms. He is supposed to solve the problem using several Python standard packages and advanced techniques.
  8.  
  9. 2Problem template
  10.  
  11. #----------------------------------------#
  12. Question
  13. Hints
  14. Solution
  15.  
  16. 3Questions
  17.  
  18. #----------------------------------------#
  19. Question 1
  20. Level 1
  21.  
  22. Question:
  23. Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5,
  24. between 2000 and 3200 (both included).
  25. The numbers obtained should be printed in a comma-separated sequence on a single line.
  26.  
  27. Hints:
  28. Consider use range(#begin, #end) method
  29.  
  30. Solution:
  31. l=[]
  32. for i in range(2000, 3201):
  33.     if (i%7==0) and (i%5!=0):
  34.         l.append(str(i))
  35.  
  36. print ','.join(l)
  37. #----------------------------------------#
  38.  
  39. #----------------------------------------#
  40. Question 2
  41. Level 1
  42.  
  43. Question:
  44. Write a program which can compute the factorial of a given numbers.
  45. The results should be printed in a comma-separated sequence on a single line.
  46. Suppose the following input is supplied to the program:
  47. 8
  48. Then, the output should be:
  49. 40320
  50.  
  51. Hints:
  52. In case of input data being supplied to the question, it should be assumed to be a console input.
  53.  
  54. Solution:
  55. def fact(x):
  56.     if x == 0:
  57.         return 1
  58.     return x * fact(x - 1)
  59.  
  60. x=int(raw_input())
  61. print fact(x)
  62. #----------------------------------------#
  63.  
  64. #----------------------------------------#
  65. Question 3
  66. Level 1
  67.  
  68. Question:
  69. With a given integral number n, write a program to generate a dictionary that contains (i, i*i) such that is an integral number between 1 and n (both included). and then the program should print the dictionary.
  70. Suppose the following input is supplied to the program:
  71. 8
  72. Then, the output should be:
  73. {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64}
  74.  
  75. Hints:
  76. In case of input data being supplied to the question, it should be assumed to be a console input.
  77. Consider use dict()
  78.  
  79. Solution:
  80. n=int(raw_input())
  81. d=dict()
  82. for i in range(1,n+1):
  83.     d[i]=i*i
  84.  
  85. print d
  86. #----------------------------------------#
  87.  
  88. #----------------------------------------#
  89. Question 4
  90. Level 1
  91.  
  92. Question:
  93. Write a program which accepts a sequence of comma-separated numbers from console and generate a list and a tuple which contains every number.
  94. Suppose the following input is supplied to the program:
  95. 34,67,55,33,12,98
  96. Then, the output should be:
  97. ['34', '67', '55', '33', '12', '98']
  98. ('34', '67', '55', '33', '12', '98')
  99.  
  100. Hints:
  101. In case of input data being supplied to the question, it should be assumed to be a console input.
  102. tuple() method can convert list to tuple
  103.  
  104. Solution:
  105. values=raw_input()
  106. l=values.split(",")
  107. t=tuple(l)
  108. print l
  109. print t
  110. #----------------------------------------#
  111.  
  112. #----------------------------------------#
  113. Question 5
  114. Level 1
  115.  
  116. Question:
  117. Define a class which has at least two methods:
  118. getString: to get a string from console input
  119. printString: to print the string in upper case.
  120. Also please include simple test function to test the class methods.
  121.  
  122. Hints:
  123. Use __init__ method to construct some parameters
  124.  
  125. Solution:
  126. class InputOutString(object):
  127.     def __init__(self):
  128.         self.s = ""
  129.  
  130.     def getString(self):
  131.         self.s = raw_input()
  132.  
  133.     def printString(self):
  134.         print self.s.upper()
  135.  
  136. strObj = InputOutString()
  137. strObj.getString()
  138. strObj.printString()
  139. #----------------------------------------#
  140.  
  141. #----------------------------------------#
  142. Question 6
  143. Level 2
  144.  
  145. Question:
  146. Write a program that calculates and prints the value according to the given formula:
  147. Q = Square root of [(2 * C * D)/H]
  148. Following are the fixed values of C and H:
  149. C is 50. H is 30.
  150. D is the variable whose values should be input to your program in a comma-separated sequence.
  151. Example
  152. Let us assume the following comma separated input sequence is given to the program:
  153. 100,150,180
  154. The output of the program should be:
  155. 18,22,24
  156.  
  157. Hints:
  158. If the output received is in decimal form, it should be rounded off to its nearest value (for example, if the output received is 26.0, it should be printed as 26)
  159. In case of input data being supplied to the question, it should be assumed to be a console input.
  160.  
  161. Solution:
  162. #!/usr/bin/env python
  163. import math
  164. c=50
  165. h=30
  166. value = []
  167. items=[x for x in raw_input().split(',')]
  168. for d in items:
  169.     value.append(str(int(round(math.sqrt(2*c*float(d)/h)))))
  170.  
  171. print ','.join(value)
  172. #----------------------------------------#
  173.  
  174. #----------------------------------------#
  175. Question 7
  176. Level 2
  177.  
  178. Question:
  179. Write a program which takes 2 digits, X,Y as input and generates a 2-dimensional array. The element value in the i-th row and j-th column of the array should be i*j.
  180. Note: i=0,1.., X-1; j=0,1,¡­Y-1.
  181. Example
  182. Suppose the following inputs are given to the program:
  183. 3,5
  184. Then, the output of the program should be:
  185. [[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]]
  186.  
  187. Hints:
  188. Note: In case of input data being supplied to the question, it should be assumed to be a console input in a comma-separated form.
  189.  
  190. Solution:
  191. input_str = raw_input()
  192. dimensions=[int(x) for x in input_str.split(',')]
  193. rowNum=dimensions[0]
  194. colNum=dimensions[1]
  195. multilist = [[0 for col in range(colNum)] for row in range(rowNum)]
  196.  
  197. for row in range(rowNum):
  198.     for col in range(colNum):
  199.         multilist[row][col]= row*col
  200.  
  201. print multilist
  202. #----------------------------------------#
  203.  
  204. #----------------------------------------#
  205. Question 8
  206. Level 2
  207.  
  208. Question:
  209. Write a program that accepts a comma separated sequence of words as input and prints the words in a comma-separated sequence after sorting them alphabetically.
  210. Suppose the following input is supplied to the program:
  211. without,hello,bag,world
  212. Then, the output should be:
  213. bag,hello,without,world
  214.  
  215. Hints:
  216. In case of input data being supplied to the question, it should be assumed to be a console input.
  217.  
  218. Solution:
  219. items=[x for x in raw_input().split(',')]
  220. items.sort()
  221. print ','.join(items)
  222. #----------------------------------------#
  223.  
  224. #----------------------------------------#
  225. Question 9
  226. Level 2
  227.  
  228. Question£º
  229. Write a program that accepts sequence of lines as input and prints the lines after making all characters in the sentence capitalized.
  230. Suppose the following input is supplied to the program:
  231. Hello world
  232. Practice makes perfect
  233. Then, the output should be:
  234. HELLO WORLD
  235. PRACTICE MAKES PERFECT
  236.  
  237. Hints:
  238. In case of input data being supplied to the question, it should be assumed to be a console input.
  239.  
  240. Solution:
  241. lines = []
  242. while True:
  243.     s = raw_input()
  244.     if s:
  245.         lines.append(s.upper())
  246.     else:
  247.         break;
  248.  
  249. for sentence in lines:
  250.     print sentence
  251. #----------------------------------------#
  252.  
  253. #----------------------------------------#
  254. Question 10
  255. Level 2
  256.  
  257. Question:
  258. Write a program that accepts a sequence of whitespace separated words as input and prints the words after removing all duplicate words and sorting them alphanumerically.
  259. Suppose the following input is supplied to the program:
  260. hello world and practice makes perfect and hello world again
  261. Then, the output should be:
  262. again and hello makes perfect practice world
  263.  
  264. Hints:
  265. In case of input data being supplied to the question, it should be assumed to be a console input.
  266. We use set container to remove duplicated data automatically and then use sorted() to sort the data.
  267.  
  268. Solution:
  269. s = raw_input()
  270. words = [word for word in s.split(" ")]
  271. print " ".join(sorted(list(set(words))))
  272. #----------------------------------------#
  273.  
  274. #----------------------------------------#
  275. Question 11
  276. Level 2
  277.  
  278. Question:
  279. Write a program which accepts a sequence of comma separated 4 digit binary numbers as its input and then check whether they are divisible by 5 or not. The numbers that are divisible by 5 are to be printed in a comma separated sequence.
  280. Example:
  281. 0100,0011,1010,1001
  282. Then the output should be:
  283. 1010
  284. Notes: Assume the data is input by console.
  285.  
  286. Hints:
  287. In case of input data being supplied to the question, it should be assumed to be a console input.
  288.  
  289. Solution:
  290. value = []
  291. items=[x for x in raw_input().split(',')]
  292. for p in items:
  293.     intp = int(p, 2)
  294.     if not intp%5:
  295.         value.append(p)
  296.  
  297. print ','.join(value)
  298. #----------------------------------------#
  299.  
  300. #----------------------------------------#
  301. Question 12
  302. Level 2
  303.  
  304. Question:
  305. Write a program, which will find all such numbers between 1000 and 3000 (both included) such that each digit of the number is an even number.
  306. The numbers obtained should be printed in a comma-separated sequence on a single line.
  307.  
  308. Hints:
  309. In case of input data being supplied to the question, it should be assumed to be a console input.
  310.  
  311. Solution:
  312. values = []
  313. for i in range(1000, 3001):
  314.     s = str(i)
  315.     if (int(s[0])%2==0) and (int(s[1])%2==0) and (int(s[2])%2==0) and (int(s[3])%2==0):
  316.         values.append(s)
  317. print ",".join(values)
  318. #----------------------------------------#
  319.  
  320. #----------------------------------------#
  321. Question 13
  322. Level 2
  323.  
  324. Question:
  325. Write a program that accepts a sentence and calculate the number of letters and digits.
  326. Suppose the following input is supplied to the program:
  327. hello world! 123
  328. Then, the output should be:
  329. LETTERS 10
  330. DIGITS 3
  331.  
  332. Hints:
  333. In case of input data being supplied to the question, it should be assumed to be a console input.
  334.  
  335. Solution:
  336. s = raw_input()
  337. d={"DIGITS":0, "LETTERS":0}
  338. for c in s:
  339.     if c.isdigit():
  340.         d["DIGITS"]+=1
  341.     elif c.isalpha():
  342.         d["LETTERS"]+=1
  343.     else:
  344.         pass
  345. print "LETTERS", d["LETTERS"]
  346. print "DIGITS", d["DIGITS"]
  347. #----------------------------------------#
  348.  
  349. #----------------------------------------#
  350. Question 14
  351. Level 2
  352.  
  353. Question:
  354. Write a program that accepts a sentence and calculate the number of upper case letters and lower case letters.
  355. Suppose the following input is supplied to the program:
  356. Hello world!
  357. Then, the output should be:
  358. UPPER CASE 1
  359. LOWER CASE 9
  360.  
  361. Hints:
  362. In case of input data being supplied to the question, it should be assumed to be a console input.
  363.  
  364. Solution:
  365. s = raw_input()
  366. d={"UPPER CASE":0, "LOWER CASE":0}
  367. for c in s:
  368.     if c.isupper():
  369.         d["UPPER CASE"]+=1
  370.     elif c.islower():
  371.         d["LOWER CASE"]+=1
  372.     else:
  373.         pass
  374. print "UPPER CASE", d["UPPER CASE"]
  375. print "LOWER CASE", d["LOWER CASE"]
  376. #----------------------------------------#
  377.  
  378. #----------------------------------------#
  379. Question 15
  380. Level 2
  381.  
  382. Question:
  383. Write a program that computes the value of a+aa+aaa+aaaa with a given digit as the value of a.
  384. Suppose the following input is supplied to the program:
  385. 9
  386. Then, the output should be:
  387. 11106
  388.  
  389. Hints:
  390. In case of input data being supplied to the question, it should be assumed to be a console input.
  391.  
  392. Solution:
  393. a = raw_input()
  394. n1 = int( "%s" % a )
  395. n2 = int( "%s%s" % (a,a) )
  396. n3 = int( "%s%s%s" % (a,a,a) )
  397. n4 = int( "%s%s%s%s" % (a,a,a,a) )
  398. print n1+n2+n3+n4
  399. #----------------------------------------#
  400.  
  401. #----------------------------------------#
  402. Question 16
  403. Level 2
  404.  
  405. Question:
  406. Use a list comprehension to square each odd number in a list. The list is input by a sequence of comma-separated numbers.
  407. Suppose the following input is supplied to the program:
  408. 1,2,3,4,5,6,7,8,9
  409. Then, the output should be:
  410. 1,3,5,7,9
  411.  
  412. Hints:
  413. In case of input data being supplied to the question, it should be assumed to be a console input.
  414.  
  415. Solution:
  416. values = raw_input()
  417. numbers = [x for x in values.split(",") if int(x)%2!=0]
  418. print ",".join(numbers)
  419. #----------------------------------------#
  420.  
  421. Question 17
  422. Level 2
  423.  
  424. Question:
  425. Write a program that computes the net amount of a bank account based a transaction log from console input. The transaction log format is shown as following:
  426. D 100
  427. W 200
  428. ¡­
  429. D means deposit while W means withdrawal.
  430. Suppose the following input is supplied to the program:
  431. D 300
  432. D 300
  433. W 200
  434. D 100
  435. Then, the output should be:
  436. 500
  437.  
  438. Hints:
  439. In case of input data being supplied to the question, it should be assumed to be a console input.
  440.  
  441. Solution:
  442. import sys
  443. netAmount = 0
  444. while True:
  445.     s = raw_input()
  446.     if not s:
  447.         break
  448.     values = s.split(" ")
  449.     operation = values[0]
  450.     amount = int(values[1])
  451.     if operation=="D":
  452.         netAmount+=amount
  453.     elif operation=="W":
  454.         netAmount-=amount
  455.     else:
  456.         pass
  457. print netAmount
  458. #----------------------------------------#
  459.  
  460. #----------------------------------------#
  461. Question 18
  462. Level 3
  463.  
  464. Question:
  465. A website requires the users to input username and password to register. Write a program to check the validity of password input by users.
  466. Following are the criteria for checking the password:
  467. 1. At least 1 letter between [a-z]
  468. 2. At least 1 number between [0-9]
  469. 1. At least 1 letter between [A-Z]
  470. 3. At least 1 character from [$#@]
  471. 4. Minimum length of transaction password: 6
  472. 5. Maximum length of transaction password: 12
  473. Your program should accept a sequence of comma separated passwords and will check them according to the above criteria. Passwords that match the criteria are to be printed, each separated by a comma.
  474. Example
  475. If the following passwords are given as input to the program:
  476. ABd1234@1,a F1#,2w3E*,2We3345
  477. Then, the output of the program should be:
  478. ABd1234@1
  479.  
  480. Hints:
  481. In case of input data being supplied to the question, it should be assumed to be a console input.
  482.  
  483. Solutions:
  484. import re
  485. value = []
  486. items=[x for x in raw_input().split(',')]
  487. for p in items:
  488.     if len(p)<6 or len(p)>12:
  489.         continue
  490.     else:
  491.         pass
  492.     if not re.search("[a-z]",p):
  493.         continue
  494.     elif not re.search("[0-9]",p):
  495.         continue
  496.     elif not re.search("[A-Z]",p):
  497.         continue
  498.     elif not re.search("[$#@]",p):
  499.         continue
  500.     elif re.search("\s",p):
  501.         continue
  502.     else:
  503.         pass
  504.     value.append(p)
  505. print ",".join(value)
  506. #----------------------------------------#
  507.  
  508. #----------------------------------------#
  509. Question 19
  510. Level 3
  511.  
  512. Question:
  513. You are required to write a program to sort the (name, age, height) tuples by ascending order where name is string, age and height are numbers. The tuples are input by console. The sort criteria is:
  514. 1: Sort based on name;
  515. 2: Then sort based on age;
  516. 3: Then sort by score.
  517. The priority is that name > age > score.
  518. If the following tuples are given as input to the program:
  519. Tom,19,80
  520. John,20,90
  521. Jony,17,91
  522. Jony,17,93
  523. Json,21,85
  524. Then, the output of the program should be:
  525. [('John', '20', '90'), ('Jony', '17', '91'), ('Jony', '17', '93'), ('Json', '21', '85'), ('Tom', '19', '80')]
  526.  
  527. Hints:
  528. In case of input data being supplied to the question, it should be assumed to be a console input.
  529. We use itemgetter to enable multiple sort keys.
  530.  
  531. Solutions:
  532. from operator import itemgetter, attrgetter
  533.  
  534. l = []
  535. while True:
  536.     s = raw_input()
  537.     if not s:
  538.         break
  539.     l.append(tuple(s.split(",")))
  540.  
  541. print sorted(l, key=itemgetter(0,1,2))
  542. #----------------------------------------#
  543.  
  544. #----------------------------------------#
  545. Question 20
  546. Level 3
  547.  
  548. Question:
  549. Define a class with a generator which can iterate the numbers, which are divisible by 7, between a given range 0 and n.
  550.  
  551. Hints:
  552. Consider use yield
  553.  
  554. Solution:
  555. def putNumbers(n):
  556.     i = 0
  557.     while i<n:
  558.         j=i
  559.         i=i+1
  560.         if j%7==0:
  561.             yield j
  562.  
  563. for i in reverse(100):
  564.     print i
  565. #----------------------------------------#
  566.  
  567. #----------------------------------------#
  568. Question 21
  569. Level 3
  570.  
  571. Question£º
  572. A robot moves in a plane starting from the original point (0,0). The robot can move toward UP, DOWN, LEFT and RIGHT with a given steps. The trace of robot movement is shown as the following:
  573. UP 5
  574. DOWN 3
  575. LEFT 3
  576. RIGHT 2
  577. ¡­
  578. The numbers after the direction are steps. Please write a program to compute the distance from current position after a sequence of movement and original point. If the distance is a float, then just print the nearest integer.
  579. Example:
  580. If the following tuples are given as input to the program:
  581. UP 5
  582. DOWN 3
  583. LEFT 3
  584. RIGHT 2
  585. Then, the output of the program should be:
  586. 2
  587.  
  588. Hints:
  589. In case of input data being supplied to the question, it should be assumed to be a console input.
  590.  
  591. Solution:
  592. import math
  593. pos = [0,0]
  594. while True:
  595.     s = raw_input()
  596.     if not s:
  597.         break
  598.     movement = s.split(" ")
  599.     direction = movement[0]
  600.     steps = int(movement[1])
  601.     if direction=="UP":
  602.         pos[0]+=steps
  603.     elif direction=="DOWN":
  604.         pos[0]-=steps
  605.     elif direction=="LEFT":
  606.         pos[1]-=steps
  607.     elif direction=="RIGHT":
  608.         pos[1]+=steps
  609.     else:
  610.         pass
  611.  
  612. print int(round(math.sqrt(pos[1]**2+pos[0]**2)))
  613. #----------------------------------------#
  614.  
  615. #----------------------------------------#
  616. Question 22
  617. Level 3
  618.  
  619. Question:
  620. Write a program to compute the frequency of the words from the input. The output should output after sorting the key alphanumerically.
  621. Suppose the following input is supplied to the program:
  622. New to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3.
  623. Then, the output should be:
  624. 2:2
  625. 3.:1
  626. 3?:1
  627. New:1
  628. Python:5
  629. Read:1
  630. and:1
  631. between:1
  632. choosing:1
  633. or:2
  634. to:1
  635.  
  636. Hints
  637. In case of input data being supplied to the question, it should be assumed to be a console input.
  638.  
  639. Solution:
  640. freq = {}   # frequency of words in text
  641. line = raw_input()
  642. for word in line.split():
  643.     freq[word] = freq.get(word,0)+1
  644.  
  645. words = freq.keys()
  646. words.sort()
  647.  
  648. for w in words:
  649.     print "%s:%d" % (w,freq[w])
  650. #----------------------------------------#
  651.  
  652. #----------------------------------------#
  653. Question 23
  654. level 1
  655.  
  656. Question:
  657.     Write a method which can calculate square value of number
  658.  
  659. Hints:
  660.     Using the ** operator
  661.  
  662. Solution:
  663. def square(num):
  664.     return num ** 2
  665.  
  666. print square(2)
  667. print square(3)
  668. #----------------------------------------#
  669.  
  670. #----------------------------------------#
  671. Question 24
  672. Level 1
  673.  
  674. Question:
  675.     Python has many built-in functions, and if you do not know how to use it, you can read document online or find some books. But Python has a built-in document function for every built-in functions.
  676.     Please write a program to print some Python built-in functions documents, such as abs(), int(), raw_input()
  677.     And add document for your own function
  678.    
  679. Hints:
  680.     The built-in document method is __doc__
  681.  
  682. Solution:
  683. print abs.__doc__
  684. print int.__doc__
  685. print raw_input.__doc__
  686.  
  687. def square(num):
  688.     '''Return the square value of the input number.
  689.    
  690.    The input number must be integer.
  691.    '''
  692.     return num ** 2
  693.  
  694. print square(2)
  695. print square.__doc__
  696. #----------------------------------------#
  697.  
  698. #----------------------------------------#
  699. Question 25
  700. Level 1
  701.  
  702. Question:
  703.     Define a class, which have a class parameter and have a same instance parameter.
  704.  
  705. Hints:
  706.     Define a instance parameter, need add it in __init__ method
  707.     You can init a object with construct parameter or set the value later
  708.  
  709. Solution:
  710. class Person:
  711.     # Define the class parameter "name"
  712.     name = "Person"
  713.    
  714.     def __init__(self, name = None):
  715.         # self.name is the instance parameter
  716.         self.name = name
  717.  
  718. jeffrey = Person("Jeffrey")
  719. print "%s name is %s" % (Person.name, jeffrey.name)
  720.  
  721. nico = Person()
  722. nico.name = "Nico"
  723. print "%s name is %s" % (Person.name, nico.name)
  724. #----------------------------------------#
  725.  
  726. #----------------------------------------#
  727. Question:
  728. Define a function which can compute the sum of two numbers.
  729.  
  730. Hints:
  731. Define a function with two numbers as arguments. You can compute the sum in the function and return the value.
  732.  
  733. Solution
  734. def SumFunction(number1, number2):
  735.     return number1+number2
  736.  
  737. print SumFunction(1,2)
  738.  
  739. #----------------------------------------#
  740. Question:
  741. Define a function that can convert a integer into a string and print it in console.
  742.  
  743. Hints:
  744.  
  745. Use str() to convert a number to string.
  746.  
  747. Solution
  748. def printValue(n):
  749.     print str(n)
  750.  
  751. printValue(3)
  752.    
  753.  
  754. #----------------------------------------#
  755. Question:
  756. Define a function that can convert a integer into a string and print it in console.
  757.  
  758. Hints:
  759.  
  760. Use str() to convert a number to string.
  761.  
  762. Solution
  763. def printValue(n):
  764.     print str(n)
  765.  
  766. printValue(3)
  767.  
  768. #----------------------------------------#
  769. 2.10
  770.  
  771. Question:
  772. Define a function that can receive two integral numbers in string form and compute their sum and then print it in console.
  773.  
  774. Hints:
  775.  
  776. Use int() to convert a string to integer.
  777.  
  778. Solution
  779. def printValue(s1,s2):
  780.     print int(s1)+int(s2)
  781.  
  782. printValue("3","4") #7
  783.  
  784.  
  785. #----------------------------------------#
  786. 2.10
  787.  
  788.  
  789. Question:
  790. Define a function that can accept two strings as input and concatenate them and then print it in console.
  791.  
  792. Hints:
  793.  
  794. Use + to concatenate the strings
  795.  
  796. Solution
  797. def printValue(s1,s2):
  798.     print s1+s2
  799.  
  800. printValue("3","4") #34
  801.  
  802. #----------------------------------------#
  803. 2.10
  804.  
  805.  
  806. Question:
  807. Define a function that can accept two strings as input and print the string with maximum length in console. If two strings have the same length, then the function should print al l strings line by line.
  808.  
  809. Hints:
  810.  
  811. Use len() function to get the length of a string
  812.  
  813. Solution
  814. def printValue(s1,s2):
  815.     len1 = len(s1)
  816.     len2 = len(s2)
  817.     if len1>len2:
  818.         print s1
  819.     elif len2>len1:
  820.         print s2
  821.     else:
  822.         print s1
  823.         print s2
  824.        
  825.  
  826. printValue("one","three")
  827.  
  828.  
  829.  
  830. #----------------------------------------#
  831. 2.10
  832.  
  833. Question:
  834. Define a function that can accept an integer number as input and print the "It is an even number" if the number is even, otherwise print "It is an odd number".
  835.  
  836. Hints:
  837.  
  838. Use % operator to check if a number is even or odd.
  839.  
  840. Solution
  841. def checkValue(n):
  842.     if n%2 == 0:
  843.         print "It is an even number"
  844.     else:
  845.         print "It is an odd number"
  846.        
  847.  
  848. checkValue(7)
  849.  
  850.  
  851. #----------------------------------------#
  852. 2.10
  853.  
  854. Question:
  855. Define a function which can print a dictionary where the keys are numbers between 1 and 3 (both included) and the values are square of keys.
  856.  
  857. Hints:
  858.  
  859. Use dict[key]=value pattern to put entry into a dictionary.
  860. Use ** operator to get power of a number.
  861.  
  862. Solution
  863. def printDict():
  864.     d=dict()
  865.     d[1]=1
  866.     d[2]=2**2
  867.     d[3]=3**2
  868.     print d
  869.        
  870.  
  871. printDict()
  872.  
  873.  
  874.  
  875.  
  876.  
  877. #----------------------------------------#
  878. 2.10
  879.  
  880. Question:
  881. Define a function which can print a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys.
  882.  
  883. Hints:
  884.  
  885. Use dict[key]=value pattern to put entry into a dictionary.
  886. Use ** operator to get power of a number.
  887. Use range() for loops.
  888.  
  889. Solution
  890. def printDict():
  891.     d=dict()
  892.     for i in range(1,21):
  893.         d[i]=i**2
  894.     print d
  895.        
  896.  
  897. printDict()
  898.  
  899.  
  900. #----------------------------------------#
  901. 2.10
  902.  
  903. Question:
  904. Define a function which can generate a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys. The function should just print the values only.
  905.  
  906. Hints:
  907.  
  908. Use dict[key]=value pattern to put entry into a dictionary.
  909. Use ** operator to get power of a number.
  910. Use range() for loops.
  911. Use keys() to iterate keys in the dictionary. Also we can use item() to get key/value pairs.
  912.  
  913. Solution
  914. def printDict():
  915.     d=dict()
  916.     for i in range(1,21):
  917.         d[i]=i**2
  918.     for (k,v) in d.items():
  919.         print v
  920.        
  921.  
  922. printDict()
  923.  
  924. #----------------------------------------#
  925. 2.10
  926.  
  927. Question:
  928. Define a function which can generate a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys. The function should just print the keys only.
  929.  
  930. Hints:
  931.  
  932. Use dict[key]=value pattern to put entry into a dictionary.
  933. Use ** operator to get power of a number.
  934. Use range() for loops.
  935. Use keys() to iterate keys in the dictionary. Also we can use item() to get key/value pairs.
  936.  
  937. Solution
  938. def printDict():
  939.     d=dict()
  940.     for i in range(1,21):
  941.         d[i]=i**2
  942.     for k in d.keys()
  943.         print k
  944.        
  945.  
  946. printDict()
  947.  
  948.  
  949. #----------------------------------------#
  950. 2.10
  951.  
  952. Question:
  953. Define a function which can generate and print a list where the values are square of numbers between 1 and 20 (both included).
  954.  
  955. Hints:
  956.  
  957. Use ** operator to get power of a number.
  958. Use range() for loops.
  959. Use list.append() to add values into a list.
  960.  
  961. Solution
  962. def printList():
  963.     li=list()
  964.     for i in range(1,21):
  965.         li.append(i**2)
  966.     print li
  967.        
  968.  
  969. printList()
  970.  
  971. #----------------------------------------#
  972. 2.10
  973.  
  974. Question:
  975. Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print the first 5 elements in the list.
  976.  
  977. Hints:
  978.  
  979. Use ** operator to get power of a number.
  980. Use range() for loops.
  981. Use list.append() to add values into a list.
  982. Use [n1:n2] to slice a list
  983.  
  984. Solution
  985. def printList():
  986.     li=list()
  987.     for i in range(1,21):
  988.         li.append(i**2)
  989.     print li[:5]
  990.        
  991.  
  992. printList()
  993.  
  994.  
  995. #----------------------------------------#
  996. 2.10
  997.  
  998. Question:
  999. Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print the last 5 elements in the list.
  1000.  
  1001. Hints:
  1002.  
  1003. Use ** operator to get power of a number.
  1004. Use range() for loops.
  1005. Use list.append() to add values into a list.
  1006. Use [n1:n2] to slice a list
  1007.  
  1008. Solution
  1009. def printList():
  1010.     li=list()
  1011.     for i in range(1,21):
  1012.         li.append(i**2)
  1013.     print li[-5:]
  1014.        
  1015.  
  1016. printList()
  1017.  
  1018.  
  1019. #----------------------------------------#
  1020. 2.10
  1021.  
  1022. Question:
  1023. Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print all values except the first 5 elements in the list.
  1024.  
  1025. Hints:
  1026.  
  1027. Use ** operator to get power of a number.
  1028. Use range() for loops.
  1029. Use list.append() to add values into a list.
  1030. Use [n1:n2] to slice a list
  1031.  
  1032. Solution
  1033. def printList():
  1034.     li=list()
  1035.     for i in range(1,21):
  1036.         li.append(i**2)
  1037.     print li[5:]
  1038.        
  1039.  
  1040. printList()
  1041.  
  1042.  
  1043. #----------------------------------------#
  1044. 2.10
  1045.  
  1046. Question:
  1047. Define a function which can generate and print a tuple where the value are square of numbers between 1 and 20 (both included).
  1048.  
  1049. Hints:
  1050.  
  1051. Use ** operator to get power of a number.
  1052. Use range() for loops.
  1053. Use list.append() to add values into a list.
  1054. Use tuple() to get a tuple from a list.
  1055.  
  1056. Solution
  1057. def printTuple():
  1058.     li=list()
  1059.     for i in range(1,21):
  1060.         li.append(i**2)
  1061.     print tuple(li)
  1062.        
  1063. printTuple()
  1064.  
  1065.  
  1066.  
  1067. #----------------------------------------#
  1068. 2.10
  1069.  
  1070. Question:
  1071. With a given tuple (1,2,3,4,5,6,7,8,9,10), write a program to print the first half values in one line and the last half values in one line.
  1072.  
  1073. Hints:
  1074.  
  1075. Use [n1:n2] notation to get a slice from a tuple.
  1076.  
  1077. Solution
  1078. tp=(1,2,3,4,5,6,7,8,9,10)
  1079. tp1=tp[:5]
  1080. tp2=tp[5:]
  1081. print tp1
  1082. print tp2
  1083.  
  1084.  
  1085. #----------------------------------------#
  1086. 2.10
  1087.  
  1088. Question:
  1089. Write a program to generate and print another tuple whose values are even numbers in the given tuple (1,2,3,4,5,6,7,8,9,10).
  1090.  
  1091. Hints:
  1092.  
  1093. Use "for" to iterate the tuple
  1094. Use tuple() to generate a tuple from a list.
  1095.  
  1096. Solution
  1097. tp=(1,2,3,4,5,6,7,8,9,10)
  1098. li=list()
  1099. for i in tp:
  1100.     if tp[i]%2==0:
  1101.         li.append(tp[i])
  1102.  
  1103. tp2=tuple(li)
  1104. print tp2
  1105.  
  1106.  
  1107.  
  1108. #----------------------------------------#
  1109. 2.14
  1110.  
  1111. Question:
  1112. Write a program which accepts a string as input to print "Yes" if the string is "yes" or "YES" or "Yes", otherwise print "No".
  1113.  
  1114. Hints:
  1115.  
  1116. Use if statement to judge condition.
  1117.  
  1118. Solution
  1119. s= raw_input()
  1120. if s=="yes" or s=="YES" or s=="Yes":
  1121.     print "Yes"
  1122. else:
  1123.     print "No"
  1124.  
  1125.  
  1126.  
  1127. #----------------------------------------#
  1128. 3.4
  1129.  
  1130. Question:
  1131. Write a program which can filter even numbers in a list by using filter function. The list is: [1,2,3,4,5,6,7,8,9,10].
  1132.  
  1133. Hints:
  1134.  
  1135. Use filter() to filter some elements in a list.
  1136. Use lambda to define anonymous functions.
  1137.  
  1138. Solution
  1139. li = [1,2,3,4,5,6,7,8,9,10]
  1140. evenNumbers = filter(lambda x: x%2==0, li)
  1141. print evenNumbers
  1142.  
  1143.  
  1144. #----------------------------------------#
  1145. 3.4
  1146.  
  1147. Question:
  1148. Write a program which can map() to make a list whose elements are square of elements in [1,2,3,4,5,6,7,8,9,10].
  1149.  
  1150. Hints:
  1151.  
  1152. Use map() to generate a list.
  1153. Use lambda to define anonymous functions.
  1154.  
  1155. Solution
  1156. li = [1,2,3,4,5,6,7,8,9,10]
  1157. squaredNumbers = map(lambda x: x**2, li)
  1158. print squaredNumbers
  1159.  
  1160. #----------------------------------------#
  1161. 3.5
  1162.  
  1163. Question:
  1164. Write a program which can map() and filter() to make a list whose elements are square of even number in [1,2,3,4,5,6,7,8,9,10].
  1165.  
  1166. Hints:
  1167.  
  1168. Use map() to generate a list.
  1169. Use filter() to filter elements of a list.
  1170. Use lambda to define anonymous functions.
  1171.  
  1172. Solution
  1173. li = [1,2,3,4,5,6,7,8,9,10]
  1174. evenNumbers = map(lambda x: x**2, filter(lambda x: x%2==0, li))
  1175. print evenNumbers
  1176.  
  1177.  
  1178.  
  1179.  
  1180. #----------------------------------------#
  1181. 3.5
  1182.  
  1183. Question:
  1184. Write a program which can filter() to make a list whose elements are even number between 1 and 20 (both included).
  1185.  
  1186. Hints:
  1187.  
  1188. Use filter() to filter elements of a list.
  1189. Use lambda to define anonymous functions.
  1190.  
  1191. Solution
  1192. evenNumbers = filter(lambda x: x%2==0, range(1,21))
  1193. print evenNumbers
  1194.  
  1195.  
  1196. #----------------------------------------#
  1197. 3.5
  1198.  
  1199. Question:
  1200. Write a program which can map() to make a list whose elements are square of numbers between 1 and 20 (both included).
  1201.  
  1202. Hints:
  1203.  
  1204. Use map() to generate a list.
  1205. Use lambda to define anonymous functions.
  1206.  
  1207. Solution
  1208. squaredNumbers = map(lambda x: x**2, range(1,21))
  1209. print squaredNumbers
  1210.  
  1211.  
  1212.  
  1213.  
  1214. #----------------------------------------#
  1215. 7.2
  1216.  
  1217. Question:
  1218. Define a class named American which has a static method called printNationality.
  1219.  
  1220. Hints:
  1221.  
  1222. Use @staticmethod decorator to define class static method.
  1223.  
  1224. Solution
  1225. class American(object):
  1226.     @staticmethod
  1227.     def printNationality():
  1228.         print "America"
  1229.  
  1230. anAmerican = American()
  1231. anAmerican.printNationality()
  1232. American.printNationality()
  1233.  
  1234.  
  1235.  
  1236.  
  1237. #----------------------------------------#
  1238.  
  1239. 7.2
  1240.  
  1241. Question:
  1242. Define a class named American and its subclass NewYorker.
  1243.  
  1244. Hints:
  1245.  
  1246. Use class Subclass(ParentClass) to define a subclass.
  1247.  
  1248. Solution:
  1249.  
  1250. class American(object):
  1251.     pass
  1252.  
  1253. class NewYorker(American):
  1254.     pass
  1255.  
  1256. anAmerican = American()
  1257. aNewYorker = NewYorker()
  1258. print anAmerican
  1259. print aNewYorker
  1260.  
  1261.  
  1262.  
  1263.  
  1264. #----------------------------------------#
  1265.  
  1266.  
  1267. 7.2
  1268.  
  1269. Question:
  1270. Define a class named Circle which can be constructed by a radius. The Circle class has a method which can compute the area.
  1271.  
  1272. Hints:
  1273.  
  1274. Use def methodName(self) to define a method.
  1275.  
  1276. Solution:
  1277.  
  1278. class Circle(object):
  1279.     def __init__(self, r):
  1280.         self.radius = r
  1281.  
  1282.     def area(self):
  1283.         return self.radius**2*3.14
  1284.  
  1285. aCircle = Circle(2)
  1286. print aCircle.area()
  1287.  
  1288.  
  1289.  
  1290.  
  1291.  
  1292.  
  1293. #----------------------------------------#
  1294.  
  1295. 7.2
  1296.  
  1297. Define a class named Rectangle which can be constructed by a length and width. The Rectangle class has a method which can compute the area.
  1298.  
  1299. Hints:
  1300.  
  1301. Use def methodName(self) to define a method.
  1302.  
  1303. Solution:
  1304.  
  1305. class Rectangle(object):
  1306.     def __init__(self, l, w):
  1307.         self.length = l
  1308.         self.width  = w
  1309.  
  1310.     def area(self):
  1311.         return self.length*self.width
  1312.  
  1313. aRectangle = Rectangle(2,10)
  1314. print aRectangle.area()
  1315.  
  1316.  
  1317.  
  1318.  
  1319. #----------------------------------------#
  1320.  
  1321. 7.2
  1322.  
  1323. Define a class named Shape and its subclass Square. The Square class has an init function which takes a length as argument. Both classes have a area function which can print the area of the shape where Shape's area is 0 by default.
  1324.  
  1325. Hints:
  1326.  
  1327. To override a method in super class, we can define a method with the same name in the super class.
  1328.  
  1329. Solution:
  1330.  
  1331. class Shape(object):
  1332.    def __init__(self):
  1333.        pass
  1334.  
  1335.    def area(self):
  1336.        return 0
  1337.  
  1338. class Square(Shape):
  1339.    def __init__(self, l):
  1340.        Shape.__init__(self)
  1341.        self.length = l
  1342.  
  1343.    def area(self):
  1344.        return self.length*self.length
  1345.  
  1346. aSquare= Square(3)
  1347. print aSquare.area()
  1348.  
  1349.  
  1350.  
  1351.  
  1352.  
  1353.  
  1354.  
  1355.  
  1356. #----------------------------------------#
  1357.  
  1358.  
  1359. Please raise a RuntimeError exception.
  1360.  
  1361. Hints:
  1362.  
  1363. Use raise() to raise an exception.
  1364.  
  1365. Solution:
  1366.  
  1367. raise RuntimeError('something wrong')
  1368.  
  1369.  
  1370.  
  1371. #----------------------------------------#
  1372. Write a function to compute 5/0 and use try/except to catch the exceptions.
  1373.  
  1374. Hints:
  1375.  
  1376. Use try/except to catch exceptions.
  1377.  
  1378. Solution:
  1379.  
  1380. def throws():
  1381.    return 5/0
  1382.  
  1383. try:
  1384.    throws()
  1385. except ZeroDivisionError:
  1386.    print "division by zero!"
  1387. except Exception, err:
  1388.    print 'Caught an exception'
  1389. finally:
  1390.    print 'In finally block for cleanup'
  1391.  
  1392.  
  1393. #----------------------------------------#
  1394. Define a custom exception class which takes a string message as attribute.
  1395.  
  1396. Hints:
  1397.  
  1398. To define a custom exception, we need to define a class inherited from Exception.
  1399.  
  1400. Solution:
  1401.  
  1402. class MyError(Exception):
  1403.    """My own exception class
  1404.  
  1405.    Attributes:
  1406.        msg  -- explanation of the error
  1407.    """
  1408.  
  1409.    def __init__(self, msg):
  1410.        self.msg = msg
  1411.  
  1412. error = MyError("something wrong")
  1413.  
  1414. #----------------------------------------#
  1415. Question:
  1416.  
  1417. Assuming that we have some email addresses in the "username@companyname.com" format, please write program to print the user name of a given email address. Both user names and company names are composed of letters only.
  1418.  
  1419. Example:
  1420. If the following email address is given as input to the program:
  1421.  
  1422. john@google.com
  1423.  
  1424. Then, the output of the program should be:
  1425.  
  1426. john
  1427.  
  1428. In case of input data being supplied to the question, it should be assumed to be a console input.
  1429.  
  1430. Hints:
  1431.  
  1432. Use \w to match letters.
  1433.  
  1434. Solution:
  1435. import re
  1436. emailAddress = raw_input()
  1437. pat2 = "(\w+)@((\w+\.)+(com))"
  1438. r2 = re.match(pat2,emailAddress)
  1439. print r2.group(1)
  1440.  
  1441.  
  1442. #----------------------------------------#
  1443. Question:
  1444.  
  1445. Assuming that we have some email addresses in the "username@companyname.com" format, please write program to print the company name of a given email address. Both user names and company names are composed of letters only.
  1446.  
  1447. Example:
  1448. If the following email address is given as input to the program:
  1449.  
  1450. john@google.com
  1451.  
  1452. Then, the output of the program should be:
  1453.  
  1454. google
  1455.  
  1456. In case of input data being supplied to the question, it should be assumed to be a console input.
  1457.  
  1458. Hints:
  1459.  
  1460. Use \w to match letters.
  1461.  
  1462. Solution:
  1463. import re
  1464. emailAddress = raw_input()
  1465. pat2 = "(\w+)@(\w+)\.(com)"
  1466. r2 = re.match(pat2,emailAddress)
  1467. print r2.group(2)
  1468.  
  1469.  
  1470.  
  1471.  
  1472. #----------------------------------------#
  1473. Question:
  1474.  
  1475. Write a program which accepts a sequence of words separated by whitespace as input to print the words composed of digits only.
  1476.  
  1477. Example:
  1478. If the following words is given as input to the program:
  1479.  
  1480. 2 cats and 3 dogs.
  1481.  
  1482. Then, the output of the program should be:
  1483.  
  1484. ['2', '3']
  1485.  
  1486. In case of input data being supplied to the question, it should be assumed to be a console input.
  1487.  
  1488. Hints:
  1489.  
  1490. Use re.findall() to find all substring using regex.
  1491.  
  1492. Solution:
  1493. import re
  1494. s = raw_input()
  1495. print re.findall("\d+",s)
  1496.  
  1497.  
  1498. #----------------------------------------#
  1499. Question:
  1500.  
  1501.  
  1502. Print a unicode string "hello world".
  1503.  
  1504. Hints:
  1505.  
  1506. Use u'strings' format to define unicode string.
  1507.  
  1508. Solution:
  1509.  
  1510. unicodeString = u"hello world!"
  1511. print unicodeString
  1512.  
  1513. #----------------------------------------#
  1514. Write a program to read an ASCII string and to convert it to a unicode string encoded by utf-8.
  1515.  
  1516. Hints:
  1517.  
  1518. Use unicode() function to convert.
  1519.  
  1520. Solution:
  1521.  
  1522. s = raw_input()
  1523. u = unicode( s ,"utf-8")
  1524. print u
  1525.  
  1526. #----------------------------------------#
  1527. Question:
  1528.  
  1529. Write a special comment to indicate a Python source code file is in unicode.
  1530.  
  1531. Hints:
  1532.  
  1533. Solution:
  1534.  
  1535. # -*- coding: utf-8 -*-
  1536.  
  1537. #----------------------------------------#
  1538. Question:
  1539.  
  1540. Write a program to compute 1/2+2/3+3/4+...+n/n+1 with a given n input by console (n>0).
  1541.  
  1542. Example:
  1543. If the following n is given as input to the program:
  1544.  
  1545. 5
  1546.  
  1547. Then, the output of the program should be:
  1548.  
  1549. 3.55
  1550.  
  1551. In case of input data being supplied to the question, it should be assumed to be a console input.
  1552.  
  1553. Hints:
  1554. Use float() to convert an integer to a float
  1555.  
  1556. Solution:
  1557.  
  1558. n=int(raw_input())
  1559. sum=0.0
  1560. for i in range(1,n+1):
  1561.    sum += float(float(i)/(i+1))
  1562. print sum
  1563.  
  1564.  
  1565. #----------------------------------------#
  1566. Question:
  1567.  
  1568. Write a program to compute:
  1569.  
  1570. f(n)=f(n-1)+100 when n>0
  1571. and f(0)=1
  1572.  
  1573. with a given n input by console (n>0).
  1574.  
  1575. Example:
  1576. If the following n is given as input to the program:
  1577.  
  1578. 5
  1579.  
  1580. Then, the output of the program should be:
  1581.  
  1582. 500
  1583.  
  1584. In case of input data being supplied to the question, it should be assumed to be a console input.
  1585.  
  1586. Hints:
  1587. We can define recursive function in Python.
  1588.  
  1589. Solution:
  1590.  
  1591. def f(n):
  1592.    if n==0:
  1593.        return 0
  1594.    else:
  1595.        return f(n-1)+100
  1596.  
  1597. n=int(raw_input())
  1598. print f(n)
  1599.  
  1600. #----------------------------------------#
  1601.  
  1602. Question:
  1603.  
  1604.  
  1605. The Fibonacci Sequence is computed based on the following formula:
  1606.  
  1607.  
  1608. f(n)=0 if n=0
  1609. f(n)=1 if n=1
  1610. f(n)=f(n-1)+f(n-2) if n>1
  1611.  
  1612. Please write a program to compute the value of f(n) with a given n input by console.
  1613.  
  1614. Example:
  1615. If the following n is given as input to the program:
  1616.  
  1617. 7
  1618.  
  1619. Then, the output of the program should be:
  1620.  
  1621. 13
  1622.  
  1623. In case of input data being supplied to the question, it should be assumed to be a console input.
  1624.  
  1625. Hints:
  1626. We can define recursive function in Python.
  1627.  
  1628.  
  1629. Solution:
  1630.  
  1631. def f(n):
  1632.    if n == 0: return 0
  1633.    elif n == 1: return 1
  1634.    else: return f(n-1)+f(n-2)
  1635.  
  1636. n=int(raw_input())
  1637. print f(n)
  1638.  
  1639.  
  1640. #----------------------------------------#
  1641.  
  1642. #----------------------------------------#
  1643.  
  1644. Question:
  1645.  
  1646. The Fibonacci Sequence is computed based on the following formula:
  1647.  
  1648.  
  1649. f(n)=0 if n=0
  1650. f(n)=1 if n=1
  1651. f(n)=f(n-1)+f(n-2) if n>1
  1652.  
  1653. Please write a program using list comprehension to print the Fibonacci Sequence in comma separated form with a given n input by console.
  1654.  
  1655. Example:
  1656. If the following n is given as input to the program:
  1657.  
  1658. 7
  1659.  
  1660. Then, the output of the program should be:
  1661.  
  1662. 0,1,1,2,3,5,8,13
  1663.  
  1664.  
  1665. Hints:
  1666. We can define recursive function in Python.
  1667. Use list comprehension to generate a list from an existing list.
  1668. Use string.join() to join a list of strings.
  1669.  
  1670. In case of input data being supplied to the question, it should be assumed to be a console input.
  1671.  
  1672. Solution:
  1673.  
  1674. def f(n):
  1675.    if n == 0: return 0
  1676.    elif n == 1: return 1
  1677.    else: return f(n-1)+f(n-2)
  1678.  
  1679. n=int(raw_input())
  1680. values = [str(f(x)) for x in range(0, n+1)]
  1681. print ",".join(values)
  1682.  
  1683.  
  1684. #----------------------------------------#
  1685.  
  1686. Question:
  1687.  
  1688. Please write a program using generator to print the even numbers between 0 and n in comma separated form while n is input by console.
  1689.  
  1690. Example:
  1691. If the following n is given as input to the program:
  1692.  
  1693. 10
  1694.  
  1695. Then, the output of the program should be:
  1696.  
  1697. 0,2,4,6,8,10
  1698.  
  1699. Hints:
  1700. Use yield to produce the next value in generator.
  1701.  
  1702. In case of input data being supplied to the question, it should be assumed to be a console input.
  1703.  
  1704. Solution:
  1705.  
  1706. def EvenGenerator(n):
  1707.    i=0
  1708.    while i<=n:
  1709.        if i%2==0:
  1710.            yield i
  1711.        i+=1
  1712.  
  1713.  
  1714. n=int(raw_input())
  1715. values = []
  1716. for i in EvenGenerator(n):
  1717.    values.append(str(i))
  1718.  
  1719. print ",".join(values)
  1720.  
  1721.  
  1722. #----------------------------------------#
  1723.  
  1724. Question:
  1725.  
  1726. Please write a program using generator to print the numbers which can be divisible by 5 and 7 between 0 and n in comma separated form while n is input by console.
  1727.  
  1728. Example:
  1729. If the following n is given as input to the program:
  1730.  
  1731. 100
  1732.  
  1733. Then, the output of the program should be:
  1734.  
  1735. 0,35,70
  1736.  
  1737. Hints:
  1738. Use yield to produce the next value in generator.
  1739.  
  1740. In case of input data being supplied to the question, it should be assumed to be a console input.
  1741.  
  1742. Solution:
  1743.  
  1744. def NumGenerator(n):
  1745.    for i in range(n+1):
  1746.        if i%5==0 and i%7==0:
  1747.            yield i
  1748.  
  1749. n=int(raw_input())
  1750. values = []
  1751. for i in NumGenerator(n):
  1752.    values.append(str(i))
  1753.  
  1754. print ",".join(values)
  1755.  
  1756.  
  1757. #----------------------------------------#
  1758.  
  1759. Question:
  1760.  
  1761.  
  1762. Please write assert statements to verify that every number in the list [2,4,6,8] is even.
  1763.  
  1764.  
  1765.  
  1766. Hints:
  1767. Use "assert expression" to make assertion.
  1768.  
  1769.  
  1770. Solution:
  1771.  
  1772. li = [2,4,6,8]
  1773. for i in li:
  1774.    assert i%2==0
  1775.  
  1776.  
  1777. #----------------------------------------#
  1778. Question:
  1779.  
  1780. Please write a program which accepts basic mathematic expression from console and print the evaluation result.
  1781.  
  1782. Example:
  1783. If the following string is given as input to the program:
  1784.  
  1785. 35+3
  1786.  
  1787. Then, the output of the program should be:
  1788.  
  1789. 38
  1790.  
  1791. Hints:
  1792. Use eval() to evaluate an expression.
  1793.  
  1794.  
  1795. Solution:
  1796.  
  1797. expression = raw_input()
  1798. print eval(expression)
  1799.  
  1800.  
  1801. #----------------------------------------#
  1802. Question:
  1803.  
  1804. Please write a binary search function which searches an item in a sorted list. The function should return the index of element to be searched in the list.
  1805.  
  1806.  
  1807. Hints:
  1808. Use if/elif to deal with conditions.
  1809.  
  1810.  
  1811. Solution:
  1812.  
  1813. import math
  1814. def bin_search(li, element):
  1815.    bottom = 0
  1816.    top = len(li)-1
  1817.    index = -1
  1818.    while top>=bottom and index==-1:
  1819.        mid = int(math.floor((top+bottom)/2.0))
  1820.        if li[mid]==element:
  1821.            index = mid
  1822.        elif li[mid]>element:
  1823.            top = mid-1
  1824.        else:
  1825.            bottom = mid+1
  1826.  
  1827.    return index
  1828.  
  1829. li=[2,5,7,9,11,17,222]
  1830. print bin_search(li,11)
  1831. print bin_search(li,12)
  1832.  
  1833.  
  1834.  
  1835.  
  1836. #----------------------------------------#
  1837. Question:
  1838.  
  1839. Please write a binary search function which searches an item in a sorted list. The function should return the index of element to be searched in the list.
  1840.  
  1841.  
  1842. Hints:
  1843. Use if/elif to deal with conditions.
  1844.  
  1845.  
  1846. Solution:
  1847.  
  1848. import math
  1849. def bin_search(li, element):
  1850.    bottom = 0
  1851.    top = len(li)-1
  1852.    index = -1
  1853.    while top>=bottom and index==-1:
  1854.        mid = int(math.floor((top+bottom)/2.0))
  1855.        if li[mid]==element:
  1856.            index = mid
  1857.        elif li[mid]>element:
  1858.            top = mid-1
  1859.        else:
  1860.            bottom = mid+1
  1861.  
  1862.    return index
  1863.  
  1864. li=[2,5,7,9,11,17,222]
  1865. print bin_search(li,11)
  1866. print bin_search(li,12)
  1867.  
  1868.  
  1869.  
  1870.  
  1871. #----------------------------------------#
  1872. Question:
  1873.  
  1874. Please generate a random float where the value is between 10 and 100 using Python math module.
  1875.  
  1876.  
  1877.  
  1878. Hints:
  1879. Use random.random() to generate a random float in [0,1].
  1880.  
  1881.  
  1882. Solution:
  1883.  
  1884. import random
  1885. print random.random()*100
  1886.  
  1887. #----------------------------------------#
  1888. Question:
  1889.  
  1890. Please generate a random float where the value is between 5 and 95 using Python math module.
  1891.  
  1892.  
  1893.  
  1894. Hints:
  1895. Use random.random() to generate a random float in [0,1].
  1896.  
  1897.  
  1898. Solution:
  1899.  
  1900. import random
  1901. print random.random()*100-5
  1902.  
  1903.  
  1904. #----------------------------------------#
  1905. Question:
  1906.  
  1907. Please write a program to output a random even number between 0 and 10 inclusive using random module and list comprehension.
  1908.  
  1909.  
  1910.  
  1911. Hints:
  1912. Use random.choice() to a random element from a list.
  1913.  
  1914.  
  1915. Solution:
  1916.  
  1917. import random
  1918. print random.choice([i for i in range(11) if i%2==0])
  1919.  
  1920.  
  1921. #----------------------------------------#
  1922. Question:
  1923.  
  1924. Please write a program to output a random number, which is divisible by 5 and 7, between 0 and 10 inclusive using random module and list comprehension.
  1925.  
  1926.  
  1927.  
  1928. Hints:
  1929. Use random.choice() to a random element from a list.
  1930.  
  1931.  
  1932. Solution:
  1933.  
  1934. import random
  1935. print random.choice([i for i in range(201) if i%5==0 and i%7==0])
  1936.  
  1937.  
  1938.  
  1939. #----------------------------------------#
  1940.  
  1941. Question:
  1942.  
  1943. Please write a program to generate a list with 5 random numbers between 100 and 200 inclusive.
  1944.  
  1945.  
  1946.  
  1947. Hints:
  1948. Use random.sample() to generate a list of random values.
  1949.  
  1950.  
  1951. Solution:
  1952.  
  1953. import random
  1954. print random.sample(range(100), 5)
  1955.  
  1956. #----------------------------------------#
  1957. Question:
  1958.  
  1959. Please write a program to randomly generate a list with 5 even numbers between 100 and 200 inclusive.
  1960.  
  1961.  
  1962.  
  1963. Hints:
  1964. Use random.sample() to generate a list of random values.
  1965.  
  1966.  
  1967. Solution:
  1968.  
  1969. import random
  1970. print random.sample([i for i in range(100,201) if i%2==0], 5)
  1971.  
  1972.  
  1973. #----------------------------------------#
  1974. Question:
  1975.  
  1976. Please write a program to randomly generate a list with 5 numbers, which are divisible by 5 and 7 , between 1 and 1000 inclusive.
  1977.  
  1978.  
  1979.  
  1980. Hints:
  1981. Use random.sample() to generate a list of random values.
  1982.  
  1983.  
  1984. Solution:
  1985.  
  1986. import random
  1987. print random.sample([i for i in range(1,1001) if i%5==0 and i%7==0], 5)
  1988.  
  1989. #----------------------------------------#
  1990.  
  1991. Question:
  1992.  
  1993. Please write a program to randomly print a integer number between 7 and 15 inclusive.
  1994.  
  1995.  
  1996.  
  1997. Hints:
  1998. Use random.randrange() to a random integer in a given range.
  1999.  
  2000.  
  2001. Solution:
  2002.  
  2003. import random
  2004. print random.randrange(7,16)
  2005.  
  2006. #----------------------------------------#
  2007.  
  2008. Question:
  2009.  
  2010. Please write a program to compress and decompress the string "hello world!hello world!hello world!hello world!".
  2011.  
  2012.  
  2013.  
  2014. Hints:
  2015. Use zlib.compress() and zlib.decompress() to compress and decompress a string.
  2016.  
  2017.  
  2018. Solution:
  2019.  
  2020. import zlib
  2021. s = 'hello world!hello world!hello world!hello world!'
  2022. t = zlib.compress(s)
  2023. print t
  2024. print zlib.decompress(t)
  2025.  
  2026. #----------------------------------------#
  2027. Question:
  2028.  
  2029. Please write a program to print the running time of execution of "1+1" for 100 times.
  2030.  
  2031.  
  2032.  
  2033. Hints:
  2034. Use timeit() function to measure the running time.
  2035.  
  2036. Solution:
  2037.  
  2038. from timeit import Timer
  2039. t = Timer("for i in range(100):1+1")
  2040. print t.timeit()
  2041.  
  2042. #----------------------------------------#
  2043. Question:
  2044.  
  2045. Please write a program to shuffle and print the list [3,6,7,8].
  2046.  
  2047.  
  2048.  
  2049. Hints:
  2050. Use shuffle() function to shuffle a list.
  2051.  
  2052. Solution:
  2053.  
  2054. from random import shuffle
  2055. li = [3,6,7,8]
  2056. shuffle(li)
  2057. print li
  2058.  
  2059. #----------------------------------------#
  2060. Question:
  2061.  
  2062. Please write a program to shuffle and print the list [3,6,7,8].
  2063.  
  2064.  
  2065.  
  2066. Hints:
  2067. Use shuffle() function to shuffle a list.
  2068.  
  2069. Solution:
  2070.  
  2071. from random import shuffle
  2072. li = [3,6,7,8]
  2073. shuffle(li)
  2074. print li
  2075.  
  2076.  
  2077.  
  2078. #----------------------------------------#
  2079. Question:
  2080.  
  2081. Please write a program to generate all sentences where subject is in ["I", "You"] and verb is in ["Play", "Love"] and the object is in ["Hockey","Football"].
  2082.  
  2083. Hints:
  2084. Use list[index] notation to get a element from a list.
  2085.  
  2086. Solution:
  2087.  
  2088. subjects=["I", "You"]
  2089. verbs=["Play", "Love"]
  2090. objects=["Hockey","Football"]
  2091. for i in range(len(subjects)):
  2092.    for j in range(len(verbs)):
  2093.        for k in range(len(objects)):
  2094.            sentence = "%s %s %s." % (subjects[i], verbs[j], objects[k])
  2095.            print sentence
  2096.  
  2097.  
  2098. #----------------------------------------#
  2099. Please write a program to print the list after removing delete even numbers in [5,6,77,45,22,12,24].
  2100.  
  2101. Hints:
  2102. Use list comprehension to delete a bunch of element from a list.
  2103.  
  2104. Solution:
  2105.  
  2106. li = [5,6,77,45,22,12,24]
  2107. li = [x for x in li if x%2!=0]
  2108. print li
  2109.  
  2110. #----------------------------------------#
  2111. Question:
  2112.  
  2113. By using list comprehension, please write a program to print the list after removing delete numbers which are divisible by 5 and 7 in [12,24,35,70,88,120,155].
  2114.  
  2115. Hints:
  2116. Use list comprehension to delete a bunch of element from a list.
  2117.  
  2118. Solution:
  2119.  
  2120. li = [12,24,35,70,88,120,155]
  2121. li = [x for x in li if x%5!=0 and x%7!=0]
  2122. print li
  2123.  
  2124.  
  2125. #----------------------------------------#
  2126. Question:
  2127.  
  2128. By using list comprehension, please write a program to print the list after removing the 0th, 2nd, 4th,6th numbers in [12,24,35,70,88,120,155].
  2129.  
  2130. Hints:
  2131. Use list comprehension to delete a bunch of element from a list.
  2132. Use enumerate() to get (index, value) tuple.
  2133.  
  2134. Solution:
  2135.  
  2136. li = [12,24,35,70,88,120,155]
  2137. li = [x for (i,x) in enumerate(li) if i%2!=0]
  2138. print li
  2139.  
  2140. #----------------------------------------#
  2141.  
  2142. Question:
  2143.  
  2144. By using list comprehension, please write a program generate a 3*5*8 3D array whose each element is 0.
  2145.  
  2146. Hints:
  2147. Use list comprehension to make an array.
  2148.  
  2149. Solution:
  2150.  
  2151. array = [[ [0 for col in range(8)] for col in range(5)] for row in range(3)]
  2152. print array
  2153.  
  2154. #----------------------------------------#
  2155. Question:
  2156.  
  2157. By using list comprehension, please write a program to print the list after removing the 0th,4th,5th numbers in [12,24,35,70,88,120,155].
  2158.  
  2159. Hints:
  2160. Use list comprehension to delete a bunch of element from a list.
  2161. Use enumerate() to get (index, value) tuple.
  2162.  
  2163. Solution:
  2164.  
  2165. li = [12,24,35,70,88,120,155]
  2166. li = [x for (i,x) in enumerate(li) if i not in (0,4,5)]
  2167. print li
  2168.  
  2169.  
  2170.  
  2171. #----------------------------------------#
  2172.  
  2173. Question:
  2174.  
  2175. By using list comprehension, please write a program to print the list after removing the value 24 in [12,24,35,24,88,120,155].
  2176.  
  2177. Hints:
  2178. Use list's remove method to delete a value.
  2179.  
  2180. Solution:
  2181.  
  2182. li = [12,24,35,24,88,120,155]
  2183. li = [x for x in li if x!=24]
  2184. print li
  2185.  
  2186.  
  2187. #----------------------------------------#
  2188. Question:
  2189.  
  2190. With two given lists [1,3,6,78,35,55] and [12,24,35,24,88,120,155], write a program to make a list whose elements are intersection of the above given lists.
  2191.  
  2192. Hints:
  2193. Use set() and "&=" to do set intersection operation.
  2194.  
  2195. Solution:
  2196.  
  2197. set1=set([1,3,6,78,35,55])
  2198. set2=set([12,24,35,24,88,120,155])
  2199. set1 &= set2
  2200. li=list(set1)
  2201. print li
  2202.  
  2203. #----------------------------------------#
  2204.  
  2205. With a given list [12,24,35,24,88,120,155,88,120,155], write a program to print this list after removing all duplicate values with original order reserved.
  2206.  
  2207. Hints:
  2208. Use set() to store a number of values without duplicate.
  2209.  
  2210. Solution:
  2211.  
  2212. def removeDuplicate( li ):
  2213.     newli=[]
  2214.     seen = set()
  2215.     for item in li:
  2216.         if item not in seen:
  2217.             seen.add( item )
  2218.             newli.append(item)
  2219.  
  2220.     return newli
  2221.  
  2222. li=[12,24,35,24,88,120,155,88,120,155]
  2223. print removeDuplicate(li)
  2224.  
  2225.  
  2226. #----------------------------------------#
  2227. Question:
  2228.  
  2229. Define a class Person and its two child classes: Male and Female. All classes have a method "getGender" which can print "Male" for Male class and "Female" for Female class.
  2230.  
  2231. Hints:
  2232. Use Subclass(Parentclass) to define a child class.
  2233.  
  2234. Solution:
  2235.  
  2236. class Person(object):
  2237.     def getGender( self ):
  2238.         return "Unknown"
  2239.  
  2240. class Male( Person ):
  2241.     def getGender( self ):
  2242.         return "Male"
  2243.  
  2244. class Female( Person ):
  2245.     def getGender( self ):
  2246.         return "Female"
  2247.  
  2248. aMale = Male()
  2249. aFemale= Female()
  2250. print aMale.getGender()
  2251. print aFemale.getGender()
  2252.  
  2253.  
  2254.  
  2255. #----------------------------------------#
  2256. Question:
  2257.  
  2258. Please write a program which count and print the numbers of each character in a string input by console.
  2259.  
  2260. Example:
  2261. If the following string is given as input to the program:
  2262.  
  2263. abcdefgabc
  2264.  
  2265. Then, the output of the program should be:
  2266.  
  2267. a,2
  2268. c,2
  2269. b,2
  2270. e,1
  2271. d,1
  2272. g,1
  2273. f,1
  2274.  
  2275. Hints:
  2276. Use dict to store key/value pairs.
  2277. Use dict.get() method to lookup a key with default value.
  2278.  
  2279. Solution:
  2280.  
  2281. dic = {}
  2282. s=raw_input()
  2283. for s in s:
  2284.     dic[s] = dic.get(s,0)+1
  2285. print '\n'.join(['%s,%s' % (k, v) for k, v in dic.items()])
  2286.  
  2287. #----------------------------------------#
  2288.  
  2289. Question:
  2290.  
  2291. Please write a program which accepts a string from console and print it in reverse order.
  2292.  
  2293. Example:
  2294. If the following string is given as input to the program:
  2295.  
  2296. rise to vote sir
  2297.  
  2298. Then, the output of the program should be:
  2299.  
  2300. ris etov ot esir
  2301.  
  2302. Hints:
  2303. Use list[::-1] to iterate a list in a reverse order.
  2304.  
  2305. Solution:
  2306.  
  2307. s=raw_input()
  2308. s = s[::-1]
  2309. print s
  2310.  
  2311. #----------------------------------------#
  2312.  
  2313. Question:
  2314.  
  2315. Please write a program which accepts a string from console and print the characters that have even indexes.
  2316.  
  2317. Example:
  2318. If the following string is given as input to the program:
  2319.  
  2320. H1e2l3l4o5w6o7r8l9d
  2321.  
  2322. Then, the output of the program should be:
  2323.  
  2324. Helloworld
  2325.  
  2326. Hints:
  2327. Use list[::2] to iterate a list by step 2.
  2328.  
  2329. Solution:
  2330.  
  2331. s=raw_input()
  2332. s = s[::2]
  2333. print s
  2334. #----------------------------------------#
  2335.  
  2336.  
  2337. Question:
  2338.  
  2339. Please write a program which prints all permutations of [1,2,3]
  2340.  
  2341.  
  2342. Hints:
  2343. Use itertools.permutations() to get permutations of list.
  2344.  
  2345. Solution:
  2346.  
  2347. import itertools
  2348. print list(itertools.permutations([1,2,3]))
  2349.  
  2350. #----------------------------------------#
  2351. Question:
  2352.  
  2353. Write a program to solve a classic ancient Chinese puzzle:
  2354. We count 35 heads and 94 legs among the chickens and rabbits in a farm. How many rabbits and how many chickens do we have?
  2355.  
  2356. Hint:
  2357. Use for loop to iterate all possible solutions.
  2358.  
  2359. Solution:
  2360.  
  2361. def solve(numheads,numlegs):
  2362.     ns='No solutions!'
  2363.     for i in range(numheads+1):
  2364.         j=numheads-i
  2365.         if 2*i+4*j==numlegs:
  2366.             return i,j
  2367.     return ns,ns
  2368.  
  2369. numheads=35
  2370. numlegs=94
  2371. solutions=solve(numheads,numlegs)
  2372. print solutions
  2373.  
  2374. #----------------------------------------#
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement