· 8 years ago · Nov 29, 2017, 04:02 PM
141. Using calendar module perform following operations.
2 a)print the 2016 calendar with space between months as 10 character.
3 b) How many leap days between the years 1980 to 2025.
4 c) Check given year is leap year or not.
5 d) print calendar of any specified month of the year 2016.
6Ans:
7import calendar
8for months in range(1,13):
9 print calendar.month(2016,months)
10print
11print "Leap days between 1980 to 2025:", calendar.leapdays(1980, 2026)
12print "2017 is leap year:", calendar.isleap(2017)
13print "month of 2016:",calendar.month(2016,3)
14
1542. Write a program to generate a Fibonacci series using a function called fib(n),
16 a) where N is user specified argument specifies number of elements in the series.
17Ans
18def fib_series(n):
19 first = 0
20 second= 1
21
22 third = 0
23 while(n>third):
24 print first,
25 total = first + second
26 first = second
27 second = total
28 third += 1
29
30n = int(raw_input().split())
31fib_series(n)
32
3343. Write a program to search given element from the list. Use your own function to search an element from list.
34 Note: Function should receive variable length arguments and search each of these arguments present in the list.
35Ans:
36def findelement(list1,a):
37 if a in list1:
38 print "Element is Present"
39 else:
40 print "Element is absent"
41
42list1 = input("Enter elements of list ")
43a= input("Enter element to be searched")
44findelement(list1,a)
45
4644. Write a program with lambda function to perform following.
47 a) Perform all the operations of basic calculator ( add, sub, multiply, divide, modulus, floor division )
48Ans:
49a, b = map(int, raw_input("Enter two numbers").split())
50add = lambda a,b: a+b
51sub = lambda a,b: a-b
52mul = lambda a,b: a*b
53div = lambda a,b: a/b
54mod = lambda a,b: a%b
55print "a+b",add(a,b)
56print "a-b",sub(a,b)
57print "a*b",mul(a,b)
58print "a/b",div(a,b)
59print "a%b",mod(a,b)
60
6145. Write a program to check given string is Palindrome or not. ( Use function Concepts and Required keyword, Default parameter concepts)
62 That is reverse the given string and check whether it is same as original string, if so then it is palindrome.
63 Example : String = "Malayalam" reverse string = "Malayalam" hence given string is palindrome.
64Ans:
65def isPal(s):
66 if s == s[::-1]:
67 print s,"is a palindrome"
68 else:
69 print s,"is NOT a palindrome"
70s=raw_input("enter atring")
71isPal(s)
72
7346. Write a function to find the biggest of 4 numbers.
74 a) All numbers are passed as arguments separately ( Required argument)
75 b) use default values for arguments ( Default arguments)
76Ans:
77def biggestnum(a,b,c,d):
78 if a>=b and a>=c and a>=d:
79 print a, "is largest"
80 elif b>=a and b>=c and b>=d:
81 print b ,"is largest"
82 elif c>=a and c>=b and c>=d:
83 print c, "is largest"
84 else:
85 print d, "is largest"
86
87biggestnum(43,56,2,76)
88
8947. Write function to extend the tuple with elements of list. Pass list and Tuple as parameter to the function.
90Ans:
91def tup_extend(tup1,list1):
92 tup3 = tup1+tuple(list1)
93 print tup3
94tup1=(1,'hello',2,'paris')
95list1=[3,'world',4,'tour']
96tup_extend(tup1,list1)
9748. Create a Calculator with the following functions.
98
99 a) Addition/subtraction/multiplication and division of two numbers
100 ( Note: Create separate function for each operation )
101 b) Find square root of a given number.( Use keyword arguments in your function)
102 c) Create a list of sub strings from a given string, such that sub strings are created with given character.
103 That is,
104 string = "Pack: My: Box: With: Good: Food"
105 Create sub strings with the delimiter character ":" such that the following sub strings are created.
106 substrlist=[Pack, My, Box, With, Good, Food]
107 Note : Function should take at least 2 parameters ( Main string and delimiter character)
108 return value from function will be list of substring.
109Ans:
110import math
111a, b = map(int, raw_input("Enter two numbers").split())
112add = lambda a,b: a+b
113sub = lambda a,b: a-b
114mul = lambda a,b: a*b
115div = lambda a,b: a/b
116mod = lambda a,b: a%b
117print "a+b",add(a,b)
118print "a-b",sub(a,b)
119print "a*b",mul(a,b)
120print "a/b",div(a,b)
121print "a%b",mod(a,b)
122
123n = float(raw_input("Enter number whose sqroot is to be found:"))
124sqroot = lambda n: math.sqrt(n)
125print "sqrt(n)", sqroot(n)
126
127string = "Pack: My: Box: With: Good: Food"
128def substrlist(string, deli):
129 return string.split(deli)
130print substrlist(string, ": ")
131
13249. Write a program to perform following file operations
133a) Open the file in read mode and read all its contents on to STDOUT.
134b) Open the file in write mode and enter 5 new lines of strings in to the new file.
135c) Open file in Append mode and add 5 lines of text into it.
136Ans:
137myfile = open("output.txt", "r")
138print myfile.read()
139myfile.close()
140
141myfile = open("sample.txt", "w")
142myfile.write("My name is Pranav")
143myfile.write("working on python")
144myfile.write("to enhance my skills")
145myfile.write("Saturday is a holiday")
146myfile.write("Sunday too is a holiday")
147myfile.close()
148
149myfile = open("output.txt", "a")
150myfile.write("My name is Pranav")
151myfile.write("working on python")
152myfile.write("to enhance my skills")
153myfile.write("Saturday is a holiday")
154myfile.write("Sunday too is a holiday")
155myfile.close()
156
15750. Write a program to open the existing file in read mode and perform following tasks,
158 a) Rad 10 character at a time and then print its current position of file object. Repeat this operation till the EOF.
159 b) Reset the file pointer after reading 100 Character from file ( Use Seek function to reset)
160 c) Open the file in read mode and start printing the contents from 5th line onwards.
161Ans:
162#a
163myfile = open("output.txt", "r")
164pointer = 0
165while(True):
166 c = myfile.read(10)
167 if not c:
168 break
169 else:
170 print c
171 pointer += 10
172 print pointer
173#b
174myfile = open("output.txt", "r")
175pointer = 0
176while(pointer<100):
177 c = myfile.read(10)
178 if not c:
179 break
180 else:
181 print c
182 pointer += 10
183 print pointer
184
185myfile.seek(0,0)
186print myfile.read(10)
187#c
188myfile = open("output.txt", "r")
189for i in range(5):
190 myfile.readline()
191
192for line in myfile:
193 print line
194
19551. In a given directory search all text files for the pattern "Treasure".
196 a) Find how many text file has the pattern.
197 b) Count how many times pattern repeats in each file
198
199 Note : Create at least 4 text file in a directory and keep the pattern in at least 2 files.
200 Repeat the pattern in the file many times.
201Ans:
202import glob
203import re
204total = 0
205for present in glob.glob("*.txt"):
206 myfile = open(present, "r")
207 strlist = myfile.read().split()
208 for i in range(len(strlist)):
209 string = re.sub(r'[?|$|.|!]',r'', strlist[i])
210 strlist[i] = string
211 if "Treasure" in strlist:
212 print present, strlist.count("Treasure")
213 total += strlist.count("Treasure")
214 else:
215 print present, 0
216 myfile.close()
217
218print "Total count:", total
219
22052. Open existing text file and reverse its contents. i.e
221 a) print the last line as first line and first line as last line ( Reverse the lines of the file )
222 b) print characters of file from last character of file till the first character of the file.(Reverse entire contents of file )
223Ans:
224#a
225strlist = list()
226for line in reversed(open("filename").readlines()):
227 print line.rstrip()
228 strlist.append(line.rstrip())
229 #b
230for string in strlist:
231 print string[::-1]
232
23353. Open the file is read & write mode and apply following functions
234 a) All 13 functions mentioned in Tutorial File object table.
235Ans:
236print "Enter file name to perform operations"
237fname=raw_input()
238f=open(fname,'rb+')
239print "***Name of file-->",f.name
240print "***File descriptor no.-->",f.fileno()
241print "***is file associated with terminal-->>",f.isatty()
242print "***Next line1 print-->",f.next()
243print "***Next line2 print-->",f.next()
244f.flush()
245f.close()
246#
247f=f=open(fname,'rb+')
248print "***read entire file:"
249print f.read()
250f.close()
251#
252f=f=open(fname,'rb+')
253print "***read first five chars frm file:"
254print f.read(5)
255f.close()
256#
257f=f=open(fname,'rb+')
258print "***readline***->:"
259print "Output of f.readline()-->",f.readline()
260print "Output of f.readlines()-->",f.readlines()
261f.close()
262#
263f=f=open(fname,'rb+')
264f.seek(0,2)
265str="Hello"
266f.write( str )
267f.seek(0,2)
268seq=["line new1","line new2"]
269f.writelines(seq)
270f.close()
271#
272f=f=open(fname,'rb+')
273print("Output after adding new line-->")
274print f.read()
275f.truncate()
276print "Output after truncate-->",f.readline()
277f.close()
27854. Write a program to handle the following exceptions in you program.
279 a) KeyboardInterrupt,
280 b) NameError
281 c) ArithmeticError
282 Note : make use of Try, except, else: statements.
283Ans:
284#a
285import time
286try:
287 while(True):
288 time.sleep(1)
289 print 1
290except KeyboardInterrupt:
291 print "KeyboardInterrupt"
292#b
293try:
294 name = input("Enter your name:")
295 print "Hello"+ name
296except NameError:
297 print "NameError"
298output:
299Enter your name:Pranav
300>>>NameError
301Enter your name:â€Pranavâ€
302>>>HelloPranav
303
304
305#c
306try:
307 c = 23/0
308except ArithmeticError:
309 print " ArithmeticError "
310
31155. Write a program for converting weight from Pound to Kilo grams.
312 a) Use assertion for the negative weight.
313 b) Use assertion to weight more than 100 KG
314Ans:
315#a
316def PoundToKg(pound):
317 try:
318 assert (pound>=0), "Negative weight not allowed"
319 return pound*0.453592
320 except AssertionError, e:
321 return e
322
323print PoundToKg(1233)
324print PoundToKg(-123)
325#b
326def PoundToKg(pound):
327 try:
328 assert (pound>=100), "Weight should be more than or equal to 100"
329 return pound*0.453592
330 except AssertionError, e:
331 return e
332
333print PoundToKg(98)
334print PoundToKg(231)
335
33656. Write a program to handle following exceptions using Try block.
337 a) IO Error while you try writing contents into the file that is opened in read mode only.
338 b) ValueError
339Ans:
340#a
341try:
342 myfile = open("Sample.txt", "r")
343 print myfile.read()
344except IOError:
345 print "Writing mode is not allowed"
346#b
347try:
348 n = int(input("Enter value:"))
349except ValueError:
350 print "ValueError"
351output:
352>>>Enter value:â€programmerâ€
353>>>ValueError
354
35557. From the Standard Exception Table of Tutorials: Try implementing all (25 ) exceptions in you program.
356 Note: Some exceptions might not work on your system.
357Ans:
358import math
359import sys
360import time
361#Exception
362try:
363 op=2/b
364except Exception:
365 print"Exception"
366#Standard error
367try:
368 f=open("xyz.txt",r)
369except StandardError:
370 print "Standard error:No file exists"
371
372#Arithmetic error
373try:
374 a=9/0
375except ArithmeticError:
376 print "Arithmetic error exception"
377
378#StopIteration
379try:
380 f=open('abc.txt','r')
381 for i in range(1,100):
382 print f.next()
383except StopIteration:
384 print "Stop Iteration Exception"
385f.close()
386#Systemexit
387try:
388 sys.exit()
389except SystemExit:
390 print "system exit exception"
391
392
393#Overflow error
394try:
395 a=math.exp(-5/3*5251321)
396except OverflowError:
397 print "Overflow error exception"
398
399#Value error
400try:
401 a=math.sqrt(-5/3)
402except ValueError:
403 print "ValueError"
404
405#Overflow error
406try:
407 a=math.exp(-2*100000000000000*123456)
408except OverflowError:
409 print "overflowerrror"
410#Zero division error
411try:
412 a=2/0
413except ZeroDivisionError:
414 print "Zero Division exception"
415
416#AssertionErrror
417try:
418 a=123
419 assert (a<50),"assertion error"
420except AssertionError:
421 print "Assertion error"
422#Attribute Error
423try:
424 raise AttributeError
425except AttributeError:
426 print "Attribute error"
427#EOF error
428try:
429 f=open("abc.txt",'r')
430 f.read()
431except EOFError:
432 print "EOF error"
433
434#import error
435try:
436 import asdf
437except ImportError:
438 print "Import error exception"
439
440
441
442#look up error
443dict = {'asdf':'txt'}
444try:
445 print dict['in']
446except LookupError:
447 print 'Lookup error'
448#index error
449try:
450 l1=[1,2,3]
451 print l1[8]
452except IndexError:
453 print "IndexOutofbound"
454
455#name error:
456try:
457 print d
458except NameError:
459 print "Name Error"
460
461#keyboard interrupt
462
463try:
464 x=input()
465 time.sleep(5)
466except KeyboardInterrupt:
467 print "Keyboard interrupt"
468
469#KeyError
470try:
471 print dict['a']
472except:
473 print 'Key Error'
474
475#Unbound Local Error
476try:
477 raise UnboundLocalError
478except UnboundLocalError:
479 print 'UnboundLocalError!'
480#IOError
481try:
482 f = open('asdf.txt', 'r')
483 f.write('something')
484except IOError:
485 print 'IOError!'
486
487#SyntaxError
488try:
489 raise SyntaxError
490except SyntaxError:
491 print 'Syntax Error !'
492
493#TypeError
494try:
495 a = 'string'
496 a = a-2
497except TypeError:
498 print 'Type Error'
499
500#ValueError
501try:
502 a = 'string'
503 print int(a)
504except ValueError:
505 print 'Value Error'
506
507#Runtime Error
508try:
509 raise RuntimeError
510except RuntimeError:
511 print 'Runtime Error occured !'
512
51358. Create file called "calc.py" which has following functions
514 i) functions to add 2 numbers
515 ii) function to find diff of 2 numbers
516 iii) function to multiply 2 numbers
517 iv) all maths operations ( Sqrt, div, floor div, modulus, primnumber)
518 v) Fibonacci series
519
520 a) Write a new program in file "maths.py" such that you import functions of file "calc.py" to your new program
521 b) Use From <module> import <function> statement to import only few function from calc module.
522Ans:
523#calc.py
524from __future__ import division
525import math
526
527def add(a,b):
528 print "a+b:", a+b
529
530def diff(a,b):
531 print "a-b:", a-b
532
533def multiply(a,b):
534 print "a*b:", a*b
535
536def sqroot(a):
537 print "sqrt(a)", math.sqrt(a)
538
539def floor_div(a,b):
540 print "a//b:", a//b
541
542def division(a,b):
543 print "a/b:", a/b
544
545def fib_series(n):
546 first = 0
547 second= 1
548
549 third = 0
550 while(n>third):
551 print first,
552 total = first + second
553 first = second
554 second = total
555 third += 1
556
557n = int(raw_input().split())
558fib_series(n)
559
560def isprime(n):
561 for i in range(2,):
562 if n%i==0:
563 print n,"not prime"
564 break
565 else:
566 print n,"is prime"
567 break
568n=int(raw_input())
569isprime(n)
570
571#math.py
572from calc import*
573add(23,15)
574diff(45,12)
575multiply(3,4)
576sqroot(25)
577floor_div(9,2)
578division(5,4)
579fib_series(10)
580print "prime_check:", isprime(10)
581
58259. Create file called "stringop.py" which has following functions
583 i) functions to sort numbers( Use loops for sorting, do not use built in function)
584 ii) function to search given element through binary search method.
585 ( Refer to net for the Binary search algorithm)
586 iii) function to reverse the given string
587
588 Write new program in file strpackage.py such that you import functions of file "stringop.py" to your new program
589Ans:
590#stringop.py
591def list_sort(arr):
592 for i in range(len(arr)-1):
593 for j in range(len(arr)-1):
594 if arr[j] > arr[j+1]:
595 temp = arr[j]
596 arr[j] = arr[j+1]
597 arr[j+1] = temp
598 print "Sorted:", arr
599
600def binarySearch(list1, item):
601 list1.sort()
602 first = 0
603 last = len(list1)-1
604 found = False
605
606 while first<=last and not found:
607 midpoint = (first+last)/2
608 if list1[midpoint] == item:
609 found = True
610 return found
611 else:
612 if item < list1[midpoint]:
613 last = midpoint-1
614 else:
615 first = midpoint+1
616 return found
617
618def list_rev(l):
619 print l.reverse()
620 print "reversed:", l
621
622# strpackage.py
623from stringop import*
624list_sort([23,81,42,51,31])
625print "binarySearch([23,81,42,51,31]):", binarySearch([23,81,42,51,31])
626list_rev([23,81,42,51,31])
627output:
628Sorted: [23, 31, 42, 51, 81]
629binarySearch([23,81,42,51,31],51): True
630None
631reversed: [81, 51, 42, 31, 23]