Guest User

Untitled

a guest
Jul 20th, 2018
644
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 33.38 KB | None | 0 0
  1. # Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5, between 2000 and 3200 (both included). The numbers obtained should be printed in a comma-separated sequence on a single line.
  2. # Hints: Consider use range(#begin, #end) method
  3.  
  4. l=[]
  5. for i in range(2000,3200):
  6. if (i%7==0) &(i%5!=0):
  7. l.append(str(i))
  8. print ','.join(l)
  9.  
  10.  
  11. # In[ ]:
  12.  
  13.  
  14. # Write a program which can compute the factorial of a given numbers. The results should be printed in a comma-separated sequence on a single line.
  15. #raw_input() function can be used for getting user(console) input
  16.  
  17. #Suppose the input is supplied to the program: 8
  18. #Then, the output should be: 40320
  19. #Hints: In case of input data being supplied to the question, it should be assumed to be a console input.
  20. x = int(input("Enter number:"))
  21.  
  22. def fact(x):
  23. if x==0:
  24. return 1
  25. return x * fact(x-1)
  26. print fact(x)
  27.  
  28.  
  29. # In[ ]:
  30.  
  31.  
  32. # 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.
  33. #Suppose the following input is supplied to the program: 8
  34. #Then, the output should be: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64}
  35. #Hints: In case of input data being supplied to the question, it should be assumed to be a console input. Consider use dict()
  36.  
  37. n = int(input("Enter number:"))
  38.  
  39. dict = {}
  40.  
  41. for i in range(1,n+1):
  42. dict[i] = i*i
  43. print dict
  44.  
  45.  
  46.  
  47. # In[ ]:
  48.  
  49.  
  50. # Write a program which accepts a sequence of comma-separated numbers from console and generate a list and a tuple which contains every number.
  51. #Suppose the following input is supplied to the program: 34,67,55,33,12,98
  52. #Then, the output should be: ['34', '67', '55', '33', '12', '98'] ('34', '67', '55', '33', '12', '98')
  53.  
  54. #Hints: In case of input data being supplied to the question, it should be assumed to be a console input. tuple() method can convert list to tuple
  55.  
  56. ## 4- Solution 1
  57. i = input("Input some comma seprated numbers : ")
  58. l = list(i)
  59. t = i
  60. print l
  61. print t
  62.  
  63.  
  64. # In[ ]:
  65.  
  66.  
  67. ## Solution 2
  68. values=raw_input("Input some comma seprated numbers : ")
  69. l=values.split(",")
  70. t=tuple(l)
  71. print l
  72. print t
  73.  
  74.  
  75. # In[ ]:
  76.  
  77.  
  78. # Define a class which has at least two methods: getString: to get a string from console input and
  79. #printString: to print the string in upper case. Also please include simple test function to test the class methods.
  80.  
  81. #Hints: Use __init__ method to construct some parameters
  82.  
  83. class iostring:
  84. def _init_(self):
  85. self.s=""
  86. def getString(self):
  87. self.s=raw_input()
  88. def printString(self):
  89. print self.s.upper()
  90.  
  91. newobj = iostring()
  92. newobj.getString()
  93.  
  94. newobj.printString()
  95.  
  96.  
  97. # In[4]:
  98.  
  99.  
  100. #Write a program that calculates and prints the value according to the given formula:
  101. """Q = Square root of [(2 * C * D)/H]
  102. Following are the fixed values of C and H: C is 50. H is 30.
  103. D is the variable whose values should be input to your program in a comma-separated sequence.
  104. Let us assume the following comma separated input sequence is given to the program: 100,150,180
  105. The output of the program should be: 18, 22, 24
  106. Hints: 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)
  107. In case of input data being supplied to the question, it should be assumed to be a console input."""
  108.  
  109. import math as mt
  110.  
  111. var = input("Enter comma seperated numbers:")
  112.  
  113. C = 50
  114. H = 30
  115. for D in list(var):
  116. print mt.sqrt((2*C*D)/H)
  117.  
  118.  
  119. # In[ ]:
  120.  
  121.  
  122. #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.
  123. """Note: i=0,1.., X-1; j=0,1,¡Y-1.
  124. Suppose the following inputs are given to the program: 3, 5
  125. Then, the output of the program should be: [[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]]
  126. Hints: In case of input data being supplied to the question, it should be assumed to be a console input in a comma-separated form."""
  127.  
  128. x= int(input("insert row \n: "))
  129. y = int(input("insert col \n: "))
  130.  
  131. def darray(r,c):
  132. array = [[i * j for j in range(c)] for i in range(r)]
  133. return array
  134. print (darray(x,y))
  135.  
  136.  
  137. # In[ ]:
  138.  
  139.  
  140. # 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.
  141. # Suppose the following input is supplied to the program: without,hello,bag,world
  142. # Then, the output should be: bag,hello,without,world
  143.  
  144. #Hints: In case of input data being supplied to the question, it should be assumed to be a console input.
  145.  
  146. l= raw_input("Enter:")
  147.  
  148. words = list(l.split(","))
  149. words.sort()
  150.  
  151. l=[]
  152. for word in words:
  153. l.append(word)
  154. print ', '.join(l)
  155.  
  156.  
  157.  
  158. # In[ ]:
  159.  
  160.  
  161. # Write a program that accepts sequence of lines as input and prints the lines after making all characters in the sentence capitalized.
  162. """AnalytixLabs, Website: www.analytixlabs.co.in Email: info@analytixlabs.co.in phone: +91-88021-73069
  163. Suppose the input is supplied to the program: Hello world
  164. Practice makes perfect
  165. Then, the output should be: HELLO WORLD
  166. PRACTICE MAKES PERFECT
  167. Hints: In case of input data being supplied to the question, it should be assumed to be a console input."""
  168.  
  169. l=[]
  170.  
  171. while True:
  172. s = raw_input("Enter a sentence:")
  173. if s:
  174. l.append(s.upper())
  175. else:
  176. break;
  177.  
  178. for sentence in l:
  179. print sentence
  180.  
  181.  
  182. # In[ ]:
  183.  
  184.  
  185. # 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.
  186. # Suppose the following input is supplied to the program: hello world and practice makes perfect and hello world again
  187. # Then, the output should be: again and hello makes perfect practice world
  188.  
  189. #Hints: In case of input data being supplied to the question, it should be assumed to be a console input.
  190. #We use set container to remove duplicated data automatically and then use sorted() to sort the data.
  191.  
  192. input_str = raw_input("Enter a string:")
  193. words = list(set(input_str.split()))
  194. words.sort()
  195.  
  196. l=[]
  197.  
  198. for word in words:
  199. l.append(word)
  200. print ' '.join(l)
  201.  
  202.  
  203. # In[ ]:
  204.  
  205.  
  206. # 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.
  207. """Suppose the input is supplied to the program: 0100,0011,1010,1001
  208. Then the output should be: 1010
  209. Notes: Assume the data is input by console.
  210. Hints: In case of input data being supplied to the question, it should be assumed to be a console input."""
  211.  
  212. binary = raw_input("Enter binary numbers:")
  213.  
  214. listbin = var.split(",")
  215.  
  216. for d in listbin:
  217. if int(d,2) % 5 == 0:
  218. print d
  219.  
  220.  
  221. # In[ ]:
  222.  
  223.  
  224. # 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.
  225. """The numbers obtained should be printed in a comma-separated sequence on a single line.
  226. Hints: In case of input data being supplied to the question, it should be assumed to be a console input."""
  227.  
  228. l= []
  229.  
  230. for i in range(1000,3001):
  231. if i % 2 ==0:
  232. l.append(str(i))
  233. print ','.join(l)
  234.  
  235.  
  236. # In[ ]:
  237.  
  238.  
  239. # Write a program that accepts a sentence and calculate the number of letters and digits.
  240. """Suppose the input is supplied to the program: hello world! 123
  241. Then, the output should be: LETTERS 10
  242. AnalytixLabs, Website: www.analytixlabs.co.in Email: info@analytixlabs.co.in phone: +91-88021-73069
  243. DIGITS 3
  244. Hints: In case of input data being supplied to the question, it should be assumed to be a console input."""
  245.  
  246. var = raw_input("Enter A Sentence:")
  247. print ("DIGITS " + str(sum(1 for l in var if l.isdigit()))) + (" LETTERS " + str(sum(1 for l in var if l.isalpha())))
  248.  
  249.  
  250. # In[ ]:
  251.  
  252.  
  253. # Write a program that accepts a sentence and calculate the number of upper case letters and lower case letters.
  254. #Suppose the following input is supplied to the program: Hello world!
  255. #Then, the output should be: UPPER CASE 1 LOWER CASE 9
  256.  
  257. #Hints: In case of input data being supplied to the question, it should be assumed to be a console input.
  258.  
  259. l = raw_input("Enter a sentence:")
  260. print ("UPPER CASE "+ str(sum(1 for word in l if word.isupper()))) + (" LOWER CASE "+ str(sum(1 for word in l if word.islower())))
  261.  
  262.  
  263. # In[ ]:
  264.  
  265.  
  266. # Write a program that computes the value of a+aa+aaa+aaaa with a given digit as the value of a.
  267. """Suppose the input is supplied to the program: 9
  268. Then, the output should be: 11106
  269. Hints: In case of input data being supplied to the question, it should be assumed to be a console input."""
  270. a = raw_input("Enter a digit:")
  271.  
  272. a1 = int("%s" % a)
  273. a2 = int("%s%s" % (a,a))
  274. a3 = int("%s%s%s" % (a,a,a))
  275. a4 = int("%s%s%s%s" % (a,a,a,a))
  276.  
  277. print a1+a2+a3+a4
  278.  
  279.  
  280. # In[ ]:
  281.  
  282.  
  283. # Use a list comprehension to square each odd number in a list. The list is input by a sequence of comma-separated numbers.
  284. """Suppose the input is supplied to the program: 1,2,3,4,5,6,7,8,9
  285. Then, the output should be: 1, 3, 5, 7, 9
  286. Hints: In case of input data being supplied to the question, it should be assumed to be a console input."""
  287.  
  288. var = input("Enter Numbers:")
  289. l= list(var)
  290. for n in l:
  291. if n % 2 !=0:
  292. a= n*n
  293. print n,a
  294.  
  295.  
  296. # In[ ]:
  297.  
  298.  
  299. # Define a class with a generator which can iterate the numbers, which are divisible by 7, between a given range 0 and n.
  300. #Hints: Consider use yield
  301.  
  302. s= int(raw_input("Enter a number:"))
  303.  
  304. def divi(s):
  305. for i in range(0,s):
  306. if i%7==0:
  307. print i
  308. print divi(s)
  309.  
  310.  
  311. # In[ ]:
  312.  
  313.  
  314. # Write a program to compute the frequency of the words from the input. The output should output after sorting the key alphanumerically.
  315. """Suppose the input is supplied to the program:
  316. New to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3.
  317. Then, the output should be:
  318. 2:2
  319. 3.:1
  320. 3?:1
  321. New:1
  322. Python:5
  323. Read:1
  324. and:1
  325. between:1
  326. choosing:1
  327. or:2
  328. to:1
  329. Hints: In case of input data being supplied to the question, it should be assumed to be a console input."""
  330.  
  331. var = raw_input("Enter a sentence:")
  332.  
  333. word = var.split()
  334. word.sort()
  335.  
  336. wordfreq = [word.count(x) for x in word]
  337.  
  338. dict(zip(word,wordfreq))
  339.  
  340.  
  341. # In[ ]:
  342.  
  343.  
  344. # Write a method which can calculate square value of number
  345. #Hints: Using the ** operator
  346.  
  347. def squa(x):
  348. return x**2
  349.  
  350.  
  351. # In[ ]:
  352.  
  353.  
  354. # 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.
  355. #But Python has a built-in document function for every built-in functions.
  356. #Please write a program to print some Python built-in functions documents, such as abs(), int(), raw_input()
  357. #And add document for your own function
  358.  
  359. #Hints: The built-in document method is __doc__
  360.  
  361. def absoluteNumber(number):
  362. return abs(number)
  363. print absoluteNumber(int(raw_input('Enter Number :')))
  364.  
  365.  
  366. print abs.__doc__
  367. print int.__doc__
  368. print raw_input.__doc__
  369.  
  370.  
  371. # In[ ]:
  372.  
  373.  
  374. # Define a class, which have a class parameter and have a same instance parameter.
  375. """Hints: Define a instance parameter, need add it in __init__ method
  376. You can init a object with construct parameter or set the value later"""
  377.  
  378. class Person:
  379. # Define the class parameter "name"
  380. name = "Person"
  381.  
  382. def __init__(self, name = None):
  383. # self.name is the instance parameter
  384. self.name = name
  385.  
  386. jeffrey = Person("Jeffrey")
  387. print "%s name is %s" % (Person.name, jeffrey.name)
  388.  
  389. nico = Person()
  390. nico.name = "Nico"
  391. print "%s name is %s" % (Person.name, nico.name)
  392.  
  393.  
  394. # In[ ]:
  395.  
  396.  
  397. # Define a function which can compute the sum of two numbers.
  398. """Hints: Define a function with two numbers as arguments. You can compute the sum in the function and return the value."""
  399.  
  400. def addition(x,y):
  401. z = x+y
  402. return z
  403.  
  404.  
  405. # In[ ]:
  406.  
  407.  
  408. # Define a function that can convert a integer into a string and print it in console.
  409. """Hints: Use str() to convert a number to string."""
  410.  
  411. def inttostr(x):
  412. y = str(x)
  413. return y
  414.  
  415.  
  416. # In[ ]:
  417.  
  418.  
  419. # Define a function that can receive two integral numbers in string form and compute their sum and then print it in console.
  420. """Hints: Use int() to convert a string to integer."""
  421.  
  422. def rec(x,y):
  423. print float(x)+float(y) #not working with int()
  424.  
  425.  
  426. # In[ ]:
  427.  
  428.  
  429. # Define a function that can accept two strings as input and concatenate them and then print it in console.
  430. """Hints: Use + to concatenate the strings"""
  431.  
  432. def twostr(x,y):
  433. z= x + y
  434. return z
  435.  
  436.  
  437.  
  438. # In[ ]:
  439.  
  440.  
  441. # 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.
  442. """Hints: Use len() function to get the length of a string"""
  443.  
  444. def length(x,y):
  445. if len(x) > len(y):
  446. print x
  447. elif len(x) < len(y):
  448. print y
  449. else:
  450. print x,y
  451.  
  452.  
  453.  
  454. # In[ ]:
  455.  
  456.  
  457. # 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".
  458. """Hints: Use % operator to check if a number is even or odd."""
  459.  
  460. def eveorodd(x):
  461. if x % 2==0:
  462. print "It is an even number"
  463. else:
  464. print "It is an odd number"
  465.  
  466.  
  467. # In[ ]:
  468.  
  469.  
  470. # 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.
  471. """Hints: Use dict[key]=value pattern to put entry into a dictionary.
  472. AnalytixLabs, Website: www.analytixlabs.co.in Email: info@analytixlabs.co.in phone: +91-88021-73069
  473. Use ** operator to get power of a number."""
  474.  
  475. def dic():
  476. d= {}
  477. for i in range(1,4):
  478. d[i]= i*i
  479. print d
  480.  
  481.  
  482. # In[ ]:
  483.  
  484.  
  485. # 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.
  486. """Hints: Use dict[key]=value pattern to put entry into a dictionary.
  487. Use ** operator to get power of a number. Use range() for loops."""
  488.  
  489. def dicsqua():
  490. d = {}
  491. for i in range(1,21):
  492. d[i] = i**2
  493. print d
  494.  
  495.  
  496. # In[ ]:
  497.  
  498.  
  499. # 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.
  500. """Hints: Use dict[key]=value pattern to put entry into a dictionary. Use ** operator to get power of a number. Use range() for loops. Use keys() to iterate keys in the dictionary. Also we can use item() to get key/value pairs."""
  501.  
  502. def dictval():
  503. d={}
  504. for i in range(1,21):
  505. d[i] = i **2
  506. print d.values()
  507.  
  508.  
  509. # In[ ]:
  510.  
  511.  
  512. # 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.
  513. """Hints: Use dict[key]=value pattern to put entry into a dictionary. Use ** operator to get power of a number. Use range() for loops. Use keys() to iterate keys in the dictionary. Also we can use item() to get key/value pairs."""
  514.  
  515. def dictkey():
  516. d={}
  517. for i in range(1,21):
  518. d[i] = i **2
  519. print d.keys()
  520.  
  521.  
  522.  
  523. # In[ ]:
  524.  
  525.  
  526. # Define a function which can generate and print a list where the values are square of numbers between 1 and 20 (both included).
  527. """Hints: Use ** operator to get power of a number. Use range() for loops. Use list.append() to add values into a list."""
  528.  
  529. def squa():
  530. l=[]
  531. for i in range(1,21):
  532. l.append(i ** 2)
  533. print l
  534.  
  535.  
  536.  
  537.  
  538.  
  539. # In[ ]:
  540.  
  541.  
  542. # 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.
  543. """Hints: Use ** operator to get power of a number. Use range() for loops. Use list.append() to add values into a list. Use [n1:n2] to slice a list"""
  544.  
  545. def listfirst():
  546. l= []
  547. for i in range(1,21):
  548. l.append(i**2)
  549. print l[:5]
  550.  
  551.  
  552. # In[ ]:
  553.  
  554.  
  555. # 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.
  556. """Hints: Use ** operator to get power of a number. Use range() for loops. Use list.append() to add values into a list. Use [n1:n2] to slice a list"""
  557.  
  558. def listlast():
  559. l=[]
  560. for i in range(1,21):
  561. l.append(i**2)
  562. print l[-5:]
  563.  
  564.  
  565. # In[ ]:
  566.  
  567.  
  568. # 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.
  569. """Hints: Use ** operator to get power of a number. Use range() for loops. Use list.append() to add values into a list. Use [n1:n2] to slice a list"""
  570.  
  571. def listsquare():
  572. l=[]
  573. for i in range(1,21):
  574. l.append(i**2)
  575. print l[5:]
  576.  
  577.  
  578. # In[ ]:
  579.  
  580.  
  581. # Define a function which can generate and print a tuple where the value are square of numbers between 1 and 20 (both included).
  582. """Hints: Use ** operator to get power of a number. Use range() for loops. Use list.append() to add values into a list. Use tuple() to get a tuple from a list."""
  583.  
  584. def tuplesquare():
  585. l = []
  586. for i in range(1,21):
  587. l.append(i**2)
  588. print tuple(l)
  589.  
  590.  
  591. # In[ ]:
  592.  
  593.  
  594. # 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.
  595. """Hints: Use [n1:n2] notation to get a slice from a tuple."""
  596.  
  597. t= tuple(range(1,11))
  598. print t[:5]
  599. print t[5:]
  600.  
  601.  
  602. # In[ ]:
  603.  
  604.  
  605. # 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).
  606. """Hints: Use "for" to iterate the tuple. Use tuple() to generate a tuple from a list."""
  607.  
  608. t = tuple(range(1,11))
  609. l= []
  610.  
  611. for i in t:
  612. if i % 2 ==0:
  613. l.append(i)
  614. print tuple(l)
  615.  
  616.  
  617. # In[ ]:
  618.  
  619.  
  620. # Write a program which accepts a string as input to print "Yes" if the string is "yes" or "YES" or "Yes", otherwise print "No".
  621. """Hints: Use if statement to judge condition."""
  622.  
  623. x = raw_input("Enter a word:")
  624. if x == "yes" or x == "YES" or x == "Yes":
  625. print "Yes"
  626. else:
  627. print "No"
  628.  
  629.  
  630.  
  631. # In[ ]:
  632.  
  633.  
  634. # 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].
  635. """Hints: use filter() to filter some elements in a list. Use lambda to define anonymous functions."""
  636.  
  637. filter(lambda x: x % 2==0, range(1,21))
  638.  
  639.  
  640. # In[ ]:
  641.  
  642.  
  643. # 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].
  644. """Hints: Use map() to generate a list. Use lambda to define anonymous functions."""
  645.  
  646. map(lambda x: x**2, range(1,21))
  647.  
  648.  
  649. # In[ ]:
  650.  
  651.  
  652. # 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].
  653. """Hints: Use map() to generate a list. Use filter() to filter elements of a list. Use lambda to define anonymous functions."""
  654.  
  655. map(lambda y:y**2, filter(lambda x: x%2==0, range(1,21)))
  656.  
  657.  
  658. # In[ ]:
  659.  
  660.  
  661. # Write a program which can filter() to make a list whose elements are even number between 1 and 20 (both included).
  662. """AnalytixLabs, Website: www.analytixlabs.co.in Email: info@analytixlabs.co.in phone: +91-88021-73069
  663. Hints: Use filter() to filter elements of a list. Use lambda to define anonymous functions."""
  664.  
  665. filter(lambda x: x%2==0, range(1,21))
  666.  
  667.  
  668. # In[ ]:
  669.  
  670.  
  671. # Write a program which can map() to make a list whose elements are square of numbers between 1 and 20 (both included).
  672. """Hints: Use map() to generate a list. Use lambda to define anonymous functions."""
  673.  
  674. map(lambda x:x**2, range(1,21))
  675.  
  676.  
  677. # In[ ]:
  678.  
  679.  
  680. # Define a class named American which has a static method called printNationality.
  681. """Hints: Use @staticmethod decorator to define class static method."""
  682.  
  683. class American():
  684. @staticmethod #
  685. def printNationality():
  686. print "America"
  687. an = American()
  688. an.printNationality()
  689. American.printNationality()
  690.  
  691.  
  692. # In[ ]:
  693.  
  694.  
  695. # Define a class named American and its subclass NewYorker.
  696. """Hints: Use class Subclass(ParentClass) to define a subclass."""
  697.  
  698. class American():
  699. pass
  700. class NewYorker(American):
  701. pass
  702.  
  703.  
  704. # In[ ]:
  705.  
  706.  
  707. #52.Define a class named Circle which can be constructed by a radius. The Circle class has a method which can compute the area.
  708. """Hints: Use def methodName(self) to define a method."""
  709.  
  710. class circle():
  711. def __init__(self,r):
  712. self.r = r
  713. def area(self):
  714. return 3.14*self.r**2
  715.  
  716. areacircle = circle(4)
  717. print areacircle.area()
  718.  
  719.  
  720. # In[ ]:
  721.  
  722.  
  723. # 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.
  724. """ Hints: Use def methodName(self) to define a method."""
  725.  
  726. class rectangle():
  727. def __init__(self,l,w):
  728. self.l = l
  729. self.w = w
  730. def area(self):
  731. return self.l*self.w
  732.  
  733. arearec = rectangle(2,3)
  734. print arearec.area()
  735.  
  736.  
  737. # In[ ]:
  738.  
  739.  
  740. # 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.
  741. """Hints: To override a method in super class, we can define a method with the same name in the super class."""
  742.  
  743. class shape():
  744. def __init__(self):
  745. pass
  746. def area(self):
  747. return 0
  748.  
  749. class square(shape):
  750. def __init__(self,l):
  751. shape.__init__(self)
  752. self.l = l
  753. def area(self):
  754. return self.l*self.l
  755.  
  756. asquare= square(3)
  757. print asquare.area()
  758.  
  759.  
  760. # In[ ]:
  761.  
  762.  
  763. # Write a function to compute 5/0 and use try/except to catch the exceptions.
  764. """Hints: Use try/except to catch exceptions."""
  765.  
  766. try:
  767. 5/0
  768. except Exception as e:
  769. print "Caught an error: " + str(e)
  770.  
  771.  
  772. # In[ ]:
  773.  
  774.  
  775. # Define a custom exception class which takes a string message as attribute.
  776. """Hints: To define a custom exception, we need to define a class inherited from Exception."""
  777.  
  778. class MyError(Exception):
  779. """My own exception class
  780.  
  781. Attributes:
  782. msg -- explanation of the error
  783. """
  784.  
  785. def __init__(self, msg):
  786. self.msg = msg
  787.  
  788. error = MyError("something wrong")
  789.  
  790.  
  791. # In[ ]:
  792.  
  793.  
  794. # 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.
  795. """If the following email address is given as input to the program: Chandra@analytixlabs.com
  796. Then, the output of the program should be: Chandra
  797. AnalytixLabs, Website: www.analytixlabs.co.in Email: info@analytixlabs.co.in phone: +91-88021-73069
  798. In case of input data being supplied to the question, it should be assumed to be a console input.
  799. Hints: Use \w to match letters."""
  800.  
  801. import re
  802. import pandas as pd
  803.  
  804. var = raw_input("Enter an email address:")
  805.  
  806. re.match("(\w+)@((\w+\.)+(com))",var).group(1)
  807.  
  808.  
  809. # In[ ]:
  810.  
  811.  
  812. # 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.
  813. """If the following email address is given as input to the program: Chandra@analytixlabs.com
  814. Then, the output of the program should be: analytixlabs
  815. In case of input data being supplied to the question, it should be assumed to be a console input.
  816. Hints: Use \w to match letters"""
  817.  
  818. var = raw_input("Enter an email address:")
  819.  
  820. re.match("(\w+)@(\w+)\.+(com)",var).group(2)
  821.  
  822.  
  823. # In[ ]:
  824.  
  825.  
  826. # Write a program which accepts a sequence of words separated by whitespace as input to print the words composed of digits only.
  827. """If the following words are given as input to the program: 2 cats and 3 dogs.
  828. Then, the output of the program should be: ['2', '3']
  829. In case of input data being supplied to the question, it should be assumed to be a console input.
  830. Hints: Use re.findall() to find all substring using regex."""
  831.  
  832. inputstr = raw_input("Enter a string:")
  833. inputstr = [x for x in var if x.isdigit()]
  834. print inputstr
  835.  
  836.  
  837. # In[ ]:
  838.  
  839.  
  840. # Print a unicode string "hello world".
  841. """Hints: Use u'strings' format to define unicode string."""
  842.  
  843. stringUni = u'hello world'
  844. print stringUni
  845.  
  846.  
  847. # In[ ]:
  848.  
  849.  
  850. # Write a program to read an ASCII string and to convert it to a unicode string encoded by utf-8.
  851. """Hints: Use unicode() function to convert."""
  852.  
  853. s = raw_input()
  854. UnicodeString = unicode( s ,"utf-8")
  855. print UnicodeString
  856.  
  857.  
  858. # In[ ]:
  859.  
  860.  
  861. # Write a special comment to indicate a Python source code file is in unicode.
  862.  
  863.  
  864.  
  865. # In[ ]:
  866.  
  867.  
  868. # 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.
  869. """Example: If the following n is given as input to the program: 10
  870. Then, the output of the program should be: 0,2,4,6,8,10
  871. Hints: Use yield to produce the next value in generator. In case of input data being supplied to the question, it should be assumed to be a console input."""
  872.  
  873. n= input("Enter a number")
  874.  
  875. l = []
  876.  
  877. for x in range(0,n):
  878. if x%2 ==0:
  879. l.append(str(x))
  880. print ','.join(l)
  881.  
  882.  
  883. # In[ ]:
  884.  
  885.  
  886. # 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.
  887. """If the following n is given as input to the program: 100
  888. Then, the output of the program should be: 0, 35, 70
  889. Hints: Use yield to produce the next value in generator. In case of input data being supplied to the question, it should be assumed to be a console input."""
  890.  
  891. n= input("Enter a number")
  892.  
  893. l = []
  894.  
  895. for x in range(0,n):
  896. if (x%5 ==0) and (x%7 ==0):
  897. l.append(str(x))
  898. print ','.join(l)
  899.  
  900.  
  901. # In[ ]:
  902.  
  903.  
  904. # Please write assert statements to verify that every number in the list [2,4,6,8] is even.
  905. """Hints: Use "assert expression" to make assertion."""
  906.  
  907. l = [2,4,6,8]
  908.  
  909. for i in l:
  910. assert i% 2 ==0
  911.  
  912.  
  913. # In[ ]:
  914.  
  915.  
  916. # Please write a program which accepts basic mathematic expression from console and print the evaluation result.
  917. """If the following string is given as input to the program: 35+3
  918. Then, the output of the program should be: 38
  919. Hints: Use eval() to evaluate an expression."""
  920.  
  921. maths = raw_input()
  922. print eval(maths)
  923.  
  924.  
  925. # In[ ]:
  926.  
  927.  
  928. # Please generate a random float where the value is between 10 and 100 using Python math module.
  929. """Hints: Use random.random() to generate a random float in [0,1]."""
  930.  
  931. import math as mt
  932. import numpy as np
  933. import random
  934.  
  935. random.random()*100
  936.  
  937.  
  938. # In[ ]:
  939.  
  940.  
  941. # Please generate a random float where the value is between 5 and 95 using Python math module.
  942. """Hints: Use random.random() to generate a random float in [0,1]."""
  943.  
  944. random.random()*100-5
  945.  
  946.  
  947. # In[ ]:
  948.  
  949.  
  950. # Please write a program to output a random even number between 0 and 10 inclusive using random module and list comprehension.
  951. """Hints: Use random.choice() to a random element from a list."""
  952.  
  953. random.choice([i for i in range(11) if i%2==0])
  954.  
  955.  
  956. # In[ ]:
  957.  
  958.  
  959. # 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.
  960. """Hints: Use random.choice() to a random element from a list."""
  961.  
  962. random.choice([i for i in range(100) if (i%5==0) and (i%7==0)])
  963.  
  964.  
  965. # In[ ]:
  966.  
  967.  
  968. # Please write a program to generate a list with 5 random numbers between 100 and 200 inclusive.
  969. """Hints: Use random.sample() to generate a list of random values."""
  970.  
  971. random.sample(range(100,201),5)
  972.  
  973.  
  974. # In[ ]:
  975.  
  976.  
  977. # Please write a program to randomly generate a list with 5 even numbers between 100 and 200 inclusive.
  978. """Hints: Use random.sample() to generate a list of random values."""
  979.  
  980. random.sample([i for i in range(100,201) if i%2==0],5)
  981.  
  982.  
  983. # In[ ]:
  984.  
  985.  
  986. # Please write a program to randomly generate a list with 5 numbers, which are divisible by 5 and 7 , between 1 and 1000 inclusive.
  987. """Hints: Use random.sample() to generate a list of random values."""
  988.  
  989. random.sample([i for i in range(1,1001) if (i%5==0) and (i%7==0)],5)
  990.  
  991.  
  992. # In[ ]:
  993.  
  994.  
  995. # Please write a program to randomly print a integer number between 7 and 15 inclusive.
  996. """Hints: Use random.randrange() to a random integer in a given range."""
  997.  
  998. random.randrange(7,16)
  999.  
  1000.  
  1001. # In[ ]:
  1002.  
  1003.  
  1004. # Please write a program to compress and decompress the string "hello world!hello world!hello world!hello world!".
  1005. """Hints: Use zlib.compress() and zlib.decompress() to compress and decompress a string."""
  1006.  
  1007. import zlib
  1008.  
  1009. s = "hello world!hello world!hello world!hello world!"
  1010.  
  1011. compress = zlib.compress(s)
  1012.  
  1013. print compress
  1014. print zlib.decompress(compress)
  1015.  
  1016.  
  1017. # In[ ]:
  1018.  
  1019.  
  1020. # Please write a program to print the running time of execution of "1+1" for 100 times.
  1021. """Hints: Use timeit() function to measure the running time."""
  1022.  
  1023. %%timeit
  1024. "for i in range(101):1+1"
  1025.  
  1026.  
  1027. # In[ ]:
  1028.  
  1029.  
  1030. # Please write a program to shuffle and print the list [3,6,7,8].
  1031. """Hints: Use shuffle() function to shuffle a list."""
  1032.  
  1033. from random import shuffle
  1034. l = [3,6,7,8]
  1035. shuffle(l)
  1036. print l
  1037.  
  1038.  
  1039. # In[ ]:
  1040.  
  1041.  
  1042. # 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"].
  1043. """Hints: Use list[index] notation to get a element from a list."""
  1044.  
  1045. subjects = ["I", "You"]
  1046. verbs = ["Play", "Love"]
  1047. objects =["Hockey","Football"]
  1048.  
  1049. for i in range(len(subjects)):
  1050. for j in range(len(verbs)):
  1051. for k in range(len(objects)):
  1052. print "%s%s%s." % (subjects[i],verbs[j],objects[k])
  1053.  
  1054.  
  1055. # In[ ]:
  1056.  
  1057.  
  1058. # Please write a program to print the list after removing delete even numbers in [5,6,77,45,22,12,24].
  1059. """Hints: Use list comprehension to delete a bunch of element from a list."""
  1060.  
  1061. l = [5,6,77,45,22,12,24]
  1062. l = [x for x in l if x % 2 !=0]
  1063. print l
  1064.  
  1065.  
  1066. # In[ ]:
  1067.  
  1068.  
  1069. # 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].
  1070. """Hints: Use list comprehension to delete a bunch of element from a list."""
  1071.  
  1072. l = [12,24,35,70,88,120,155]
  1073. l = [x for x in l if (x%5 !=0) and (x%7!=0)]
  1074. print l
  1075.  
  1076.  
  1077.  
  1078. # In[ ]:
  1079.  
  1080.  
  1081. # 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].
  1082. """Hints: Use list comprehension to delete a bunch of element from a list. Use enumerate() to get (index, value) tuple."""
  1083.  
  1084. l = [12,24,35,70,88,120,155]
  1085. l = [x for i,x in enumerate(l) if i not in (0,2,4,6)]
  1086. print l
  1087.  
  1088.  
  1089. # In[ ]:
  1090.  
  1091.  
  1092. # By using list comprehension, please write a program generate a 3*5*8 3D array whose each element is 0.
  1093. """Hints: Use list comprehension to make an array."""
  1094.  
  1095. import numpy as np
  1096. np.zeros([3,5,8])
  1097.  
  1098.  
  1099. # In[ ]:
  1100.  
  1101.  
  1102. # 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].
  1103. """Hints: Use list comprehension to delete a bunch of element from a list. Use enumerate() to get (index, value) tuple."""
  1104.  
  1105. l = [12,24,35,70,88,120,155]
  1106. l = [x for i,x in enumerate(l) if i not in (0,4,5)]
  1107. print l
  1108.  
  1109.  
  1110. # In[ ]:
  1111.  
  1112.  
  1113. # 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].
  1114. """Hints: Use list's remove method to delete a value."""
  1115.  
  1116. l = [12,24,35,24,88,120,155]
  1117. l = [x for x in l if x !=24]
  1118. print l
  1119.  
  1120.  
  1121. # In[ ]:
  1122.  
  1123.  
  1124. # 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.
  1125. """Hints: Use set() and "&=" to do set intersection operation."""
  1126.  
  1127. a = set([1,3,6,78,35,55])
  1128. b = a.intersection([12,24,35,24,88,120,155])
  1129. b
  1130.  
  1131.  
  1132. # In[ ]:
  1133.  
  1134.  
  1135. # 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.
  1136. """Hints: Use set() to store a number of values without duplicate."""
  1137.  
  1138. l = [12, 24, 35, 24, 88, 120, 155, 88, 120, 155]
  1139. order = list(set(l))
  1140. order.reverse()
  1141. order
  1142.  
  1143.  
  1144. # In[ ]:
  1145.  
  1146.  
  1147. # 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.
  1148. """Hints: Use Subclass(Parentclass) to define a child class."""
  1149.  
  1150. class Person():
  1151. def getGender(self):
  1152. print "Unknown"
  1153.  
  1154. class Male(Person):
  1155. def getGender(self):
  1156. print "Male"
  1157.  
  1158. class Female(Person):
  1159. def getGender(self):
  1160. print "Female"
  1161.  
  1162. aMale = Male()
  1163. aFemale= Female()
  1164. print aMale.getGender()
  1165. print aFemale.getGender()
  1166.  
  1167.  
  1168. # In[ ]:
  1169.  
  1170.  
  1171. # Please write a program which count and print the numbers of each character in a string input by console.
  1172. """If the following string is given as input to the program: abcdefgabc
  1173. Then, the output of the program should be:
  1174. a,2
  1175. c,2
  1176. b,2
  1177. e,1
  1178. d,1
  1179. g,1
  1180. f,1
  1181. Hints: Use dict to store key/value pairs. Use dict.get() method to lookup a key with default value."""
  1182.  
  1183.  
  1184. var = raw_input("Enter a string:")
  1185. charfreq = [var.count(x) for x in var]
  1186. d=dict(zip(var,charfreq))
  1187. print d
  1188.  
  1189.  
  1190. # In[ ]:
  1191.  
  1192.  
  1193. # Please write a program which accepts a string from console and print it in reverse order.
  1194. """If the following string is given as input to the program: rise to vote sir
  1195. Then, the output of the program should be: ris etov ot esir
  1196. Hints: Use list[::-1] to iterate a list in a reverse order."""
  1197.  
  1198. inputrev = raw_input("Enter a string:")
  1199. inputrev[::-1]
  1200.  
  1201.  
  1202. # In[ ]:
  1203.  
  1204.  
  1205. # Please write a program which accepts a string from console and print the characters that have even indexes.
  1206. """AnalytixLabs, Website: www.analytixlabs.co.in Email: info@analytixlabs.co.in phone: +91-88021-73069
  1207. If the following string is given as input to the program: H1e2l3l4o5w6o7r8l9d
  1208. Then, the output of the program should be: Helloworld
  1209. Hints: Use list[::2] to iterate a list by step 2."""
  1210.  
  1211. inputstr = raw_input("Enter a string:")
  1212. inputstr[::2]
  1213.  
  1214.  
  1215. # In[ ]:
  1216.  
  1217.  
  1218. # Create a dictionary with phone numbers (phonebook = {“John”: 938477566, "Jack”: 938377264, "Jill”: 947662781}). Add "Jake" to the phonebook with the phone number 938273443, and remove Jill from the phonebook.
  1219.  
  1220. phonebook = {"John":938477566, "Jack":938377264, "Jill": 947662781}
  1221.  
  1222. phonebook["Jake"] = 938273443
  1223.  
  1224. del phonebook["Jill"]
Add Comment
Please, Sign In to add comment