Question:
Write a python program to print only those lines in a list of files that has a particular word
Here, I am looking for a word ‘print’ in a list of python files.
Program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
def readfiles(filenames): for f in filenames: for line in open(f): yield line def grep(pattern, lines): return (line for line in lines if pattern in line) def printlines(lines): for line in lines: print line, def main(pattern, filenames): lines = readfiles(filenames) lines = grep(pattern, lines) printlines(lines) main('print',['factorial.py','GCD.py','LCM.py','password.py','rect.py']) |
Explanation:
Generator Expressions are generator version of list comprehensions. They look like list comprehensions, but returns a generator back instead of a list.
Output:
1 2 3 4 5 6 7 |
print "Sorry, factorial does not exist for negative numbers" print "The factorial of 0 is 1" print "The factorial of",num,"is",factorial(num) print "The H.C.F. of", n1,"and", n2,"is",HCF(n1, n2) print "The L.C.M. of", nos1,"and", nos2,"is", lcm(nos1, nos2) print "Valid passwords",value print "Area of rectangle:",obj.area() |
Question:
Write a program to trace all calls to the below function
1 2 3 4 5 |
def fib(n): if n is 0 or n is 1: return 1 else: return fib(n-1) + fib(n-2) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
def fib(n): if n is 0 or n is 1: return 1 else: return fib(n-1) + fib(n-2) def trace(f): f.indent = 0 def g(x): print '| ' * f.indent + '|--', f.__name__, x f.indent += 1 value = f(x) print '| ' * f.indent + '|--', 'return', repr(value) f.indent -= 1 return value return g fib = trace(fib) print fib(input("Enter the limit:")) |
1 2 3 4 5 6 7 8 9 10 11 12 |
Enter the limit:3 |-- fib 3 | |-- fib 2 | | |-- fib 1 | | | |-- return 1 | | |-- fib 0 | | | |-- return 1 | | |-- return 2 | |-- fib 1 | | |-- return 1 | |-- return 3 3 |
Question:
Write a python program which will find all such numbers which are divisible by 7 but are not a multiple of 5, between 1500 and 3000 (both included).
Program:
1 2 3 4 5 6 |
l=[] for i in range(1500, 3001): if (i%7==0) and (i%5!=0): l.append(str(i)) print ','.join(l) |
1 2 3 4 5 6 7 8 9 10 11 12 |
: 1512,1519,1526,1533,1547,1554,1561,1568,1582,1589,1596,1603,1617,1624,1631,1638, 1652,1659,1666,1673,1687,1694,1701,1708,1722,1729,1736,1743,1757,1764,1771,1778, 1792,1799,1806,1813,1827,1834,1841,1848,1862,1869,1876,1883,1897,1904,1911,1918, 1932,1939,1946,1953,1967,1974,1981,1988,2002,2009,2016,2023,2037,2044,2051,2058, 2072,2079,2086,2093,2107,2114,2121,2128,2142,2149,2156,2163,2177,2184,2191,2198, 2212,2219,2226,2233,2247,2254,2261,2268,2282,2289,2296,2303,2317,2324,2331,2338, 2352,2359,2366,2373,2387,2394,2401,2408,2422,2429,2436,2443,2457,2464,2471,2478, 2492,2499,2506,2513,2527,2534,2541,2548,2562,2569,2576,2583,2597,2604,2611,2618, 2632,2639,2646,2653,2667,2674,2681,2688,2702,2709,2716,2723,2737,2744,2751,2758, 2772,2779,2786,2793,2807,2814,2821,2828,2842,2849,2856,2863,2877,2884,2891,2898, 2912,2919,2926,2933,2947,2954,2961,2968,2982,2989,2996 |
Question;
With two given lists ([6,5,6,2,2]) and ([9,5,6,7,9,2,7,0]), write a python program to make a list whose elements are intersection of the another list.
Program:
1 2 3 4 5 |
set1=set([6,5,6,2,2]) set2=set([9,5,6,7,9,2,7,0]) set1 &= set2 li=list(set1) print (li) |
Explanation:
Use set() and “&=” to do set intersection operation.
Output:
1 |
[2, 5, 6] |
Question:
Write a python program to find whether a given year is a leap year or not
Program:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# Python program to check if the input year is a leap year or not year = int(input("Enter a year: ")) if (year % 4) == 0: if (year % 100) == 0: if (year % 400) == 0: print("{0} is a leap year".format(year)) else: print("{0} is not a leap year".format(year)) else: print("{0} is a leap year".format(year)) else: print("{0} is not a leap year".format(year)) |
Explanation:
A leap year is a calendar year containing one additional day added to keep the calendar year synchronized with the astronomical or seasonal year. 2016 is a leap year, which means that it has 366 days instead of the usual 365 days that an ordinary year has. An extra day is added in a leap year—February 29 —which is called an intercalary day or a leap day.
Output:
1.
1 2 |
Enter a year: 2010 2010 is not a leap year |
1 2 |
Enter a year: 2012 2012 is a leap year |
Question:
Write a program which can filter even numbers in a list by using filter function. The list is: [11,12,13,14,15,16,17,18,19,20]. Use filter() to filter some elements in a list. Use lambda to define anonymous functions.
Program:
1 2 3 |
li = [1,2,3,4,5,6,7,8,9,10] evenNumbers = filter(lambda x: x%2==0, li) print evenNumbers |
Explanation:
The function filter(function, list) offers an elegant way to filter out all the elements of a list for which the function function returns True.
The function filter(f,l) needs a function f as its first argument. f returns a Boolean value, i.e. either True or False. This function will be applied to every element of the list l. Only if f returns True, the element of the list be included in the result list.
Output:
1 |
[12, 14, 16, 18, 20] |
Question:
Display powers of two using anonymous function
Program:
1 2 3 4 5 6 7 8 9 10 11 12 |
# Python Program to display the powers of 2 using anonymous function terms = int(input("How many terms? ")) # use anonymous function result = list(map(lambda x: 2 ** x, range(terms))) # display the result print("The total terms is:",terms) for i in range(terms): print("2 raised to power",i,"is",result[i]) |
Explanation:
The lambda operator or lambda function is a way to create small anonymous functions, i.e. functions without a name. These functions are throw-away functions, i.e. they are just needed where they have been created.
The general syntax of a lambda function is quite simple:
lambda argument_list: expression
The argument list consists of a comma separated list of arguments and the expression is an arithmetic expression using these arguments. You can assign the function to a variable to give it a name.
Output:
1 2 3 4 5 6 7 |
How many terms? 5 ('The total terms is:', 5) ('2 raised to power', 0, 'is', 1) ('2 raised to power', 1, 'is', 2) ('2 raised to power', 2, 'is', 4) ('2 raised to power', 3, 'is', 8) ('2 raised to power', 4, 'is', 16) |
Question:
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.Note: i=0,1…. X-1; j=0,1…,Y-1.
Also input is in a comma-separated form.
Program:
1 2 3 4 5 6 7 8 9 10 |
input_str = raw_input() dimensions=[int(x) for x in input_str.split(',')] rowNum=dimensions[0] colNum=dimensions[1] multilist = [[0 for col in range(colNum)] for row in range(rowNum)] for row in range(rowNum): for col in range(colNum): multilist[row][col]= row*col print multilist |
Explanation:
Range function generates a list of numbers, which is generally used to iterate over with for loops.
Output:
1 2 |
3,5 [[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]] |
Question:
Write a program to sort the list [58,6,78,12,333] using binary search and return index position of 12
Program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
import math def bin_search(li, element): bottom = 0 top = len(li)-1 index = -1 while top>=bottom and index==-1: mid = top+bottom/2 if li[mid]==element: index = mid elif li[mid]>element: top = mid-1 else: bottom = mid+1 return index li=[58,6,78,12,333] print bin_search(li,12) |
Explanation:
Binary Search: Search a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array. If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half. Otherwise narrow it to the upper half. Repeatedly check until the value is found or the interval is empty.
Output:
1 |
3 |
Question:
Write a program to compress and decompress the string “Global SQA!Global SQA!Global SQA!Global SQA!Global SQA!Global SQA!”
Use zlib.compress() and zlib.decompress() to compress and decompress a string.
Program:
1 2 3 4 5 6 7 8 9 |
import zlib s = 'Global SQA!Global SQA!Global SQA!Global SQA!Global SQA!Global SQA!' t = zlib.compress(s.encode()) print (t) print (zlib.decompress(t)) |
Explanation:
zlib.
compressobj
([level[, method[, wbits[, memlevel[, strategy]]]]])
Returns a compression object, to be used for compressing data streams that won’t fit into memory at once.
zlib.
decompress
(string[, wbits[, bufsize]])
Decompresses the data in string, returning a string containing the uncompressed data.
Output:
1 2 3 |
b"x\x9cs\xcf\xc9OJ\xccQ\x08\x0etTt'\x8f\t\x00\xc5\xa1\x14\xcb" b'Global SQA!Global SQA!Global SQA!Global SQA!Global SQA!Global SQA!' |
Question:
Display calender using in-built functions
Program:
1 2 3 4 5 6 7 8 9 |
# Python program to display calendar of given month of the year # import module import calendar yy = int(input("Enter year: ")) mm = int(input("Enter month: ")) # display the calendar print(calendar.month(yy, mm)) |
Explanation:
Module calendar is imported and the function month() is used to print the month calendar.
Output:
1 2 3 4 5 6 7 8 9 |
Enter year: 2016 Enter month: 7 July 2016 Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
Question:
Write a program that accepts a sentence and calculate the number of letters and digits.
Program:
1 2 3 4 5 6 7 8 9 10 11 |
st = raw_input("Enter string:\n") d={"DIGITS":0, "LETTERS":0} for c in st: if c.isdigit(): d["DIGITS"]+=1 elif c.isalpha(): d["LETTERS"]+=1 else: pass print "LETTERS", d["LETTERS"] print "DIGITS", d["DIGITS"] |
Explanation:
Function isdigit() checks whether the concerned character is a digit, while isalpha checks whether it is an alphabet
Output:
1 2 3 4 |
Enter string: hai and hello! Welcome to the 1 and only GlobalSQA! LETTERS 39 DIGITS 1 |
Question:
Write a function to compute 1 /0 and use try/except to catch the exceptions.
Program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
def throw(): return 1/0 try: throw() except ZeroDivisionError: print "Division by zero!" except Exception, err: print 'Caught an exception' finally: print 'finally' |
Explanation:
Even if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it. Errors detected during execution are called exceptions and are not unconditionally fatal.
A try
statement may have more than one except clause, to specify handlers for different exceptions. At most one handler will be executed. Handlers only handle exceptions that occur in the corresponding try clause, not in other handlers of the same try
statement. An except clause may name multiple exceptions as a parenthesized tuple.
Output:
1 2 |
Division by zero! finally |
Question:
Write python program to print the user name of a given email address.
Program:
1 2 3 4 5 6 7 8 9 |
import re emailAddress = raw_input("Enter email addresses: ") pat2 = "(\w+)@((\w+\.)+(com))" r2 = re.match(pat2,emailAddress) print r2.group(1) |
Email addresses are in the “[email protected]” format.
Both user names and company names are composed of letters only.
Use \w to match letters.
Output:
1 2 3 |
Enter email addresses: hi@globalsql.com hi |
Question:
Raise Assertion error when trying to verify that every number in the list [2,4,6,8,1] is even.
Use “assert expression” to make assertion
Program:
1 2 3 4 5 |
li = [2,4,6,8,1] for i in li: assert i%2==0 |
Explanation:
The Assert Statement: When python encounters an assert statement, Python evaluates the accompanying expression, which is hopefully true. If the expression is false, Python raises an AssertionError exception.
Output:
1 2 3 4 5 6 7 |
Traceback (most recent call last): File "assert.py", line 4, in <module> assert i%2==0 AssertionError |
Question:
Write a program to print the squares of the numbers in a list [1,2,3,4,5] without using any iterative function.,
Program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
#creates generator def squaregenerator(nums): for i in nums: #yield keyword makes it a generator yield(i*i) #no need of return as it is generator #our data my_nums = [1,2,3,4,5] res2=squaregenerator(my_nums) print res2 print next(res2) print next(res2) print next(res2) print next(res2) print next(res2) <span style="color: #000000;"><strong>Explanation:</strong></span> <span style="color: #000000;">Generators are very easy to implement, but a bit difficult to understand.</span> <span style="color: #000000;">Generators are used to create iterators, but with a different approach. Generators are simple functions which return an iterable set of items, one at a time, in a special way.</span> <span style="color: #000000;">When an iteration iterate over a set of item starts using <strong>for</strong> statement, the generator runs. Once the generator's function code reaches a "yield" statement, the generator yields its execution back to the <strong>for</strong> loop, returning a new value from the set. The generator function can generate as many values (possibly infinite) as it wants, yielding each one in its turn.</span> <span style="color: #000000;"><strong>Output:</strong></span> |
1 2 3 4 5 6 |
<generator object squaregenerator at 0x2ac4a8d49820> 1 4 9 16 25 |
Question:
Write a python program to show the difference in zip() and izip() function
Explanation:
zip() is a standard library which combines elements into tuples.
The izip() function works the same way, but it returns an iterable object for an increase in performance by reducing memory usage.
We can directly print the list returned by zip() but, we cannot directly print an iterable object. We need to use next(iterable_object) or a loop.
Lists are stored in memory so they have the advantage of faster access times over Iterable Object whose contents are not entirely stored in memory but fetched on-demand instead.
Program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
from itertools import izip #import izip to use it in the program list1=[1,2,3] list2=['a','b','c'] print "PRINTING INITIAL LISTS" print list1 print list2 x=zip(list1,list2) print "\n\nzip() PERFORMED" #zip() combines elements of list1 and list2 into tuples and returns a list of tuples which you can directly print print "PRINTING LIST OF TUPLES" print x x=izip(list1,list2) print "\n\nizip() PERFORMED" #izip() does almost same thing as zip() but it returns a iterlist.izip object which is iterable using next() or using loops print x #cant print contents of iterable object directly print "\nUSING LOOP TO PRINT CONTENTS OF izip OBJECT" for i in x: print i |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
PRINTING INITIAL LISTS [1, 2, 3] ['a', 'b', 'c'] zip() PERFORMED PRINTING LIST OF TUPLES [(1, 'a'), (2, 'b'), (3, 'c')] izip() PERFORMED <itertools.izip object at 0x2ae4fc5dcb48> USING LOOP TO PRINT CONTENTS OF izip OBJECT (1, 'a') (2, 'b') (3, 'c') |
Question:
Write a python program to solve a quadratic equation
Program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
# Solve the quadratic equation ax**2 + bx + c = 0 # import complex math module import cmath a = float(input('Enter a: ')) b = float(input('Enter b: ')) c = float(input('Enter c: ')) # calculate the discriminant d = (b**2) - (4*a*c) # find two solutions s1 = (-b-cmath.sqrt(d))/(2*a) s2 = (-b+cmath.sqrt(d))/(2*a) print('The solution are {0} and {1}'.format(s1,s2)) |
Explanation:
Quadratic Equations is a equation having form like ax2 + bx+c =0. Roots are of the form x = (-b +/-√(b2 – 4ac))/2a. To know more about Quadratic Equations, click here.
Output:
1 2 3 4 |
Enter a: 1 Enter b: 5 Enter c: 6 The solutions are (-3+0j) and (-2+0j) |
Question:
Write a python program to convert Fahrenheit to Celsius
Program:
1 2 3 4 5 |
Fahrenheit = int(raw_input("Enter a temperature in Fahrenheit: ")) Celsius = (Fahrenheit - 32) * 5.0/9.0 print "Temperature:", Fahrenheit, "Fahrenheit = ", Celsius, " C" |
Explanation:
To convert the temperature from Fahrenheit to Celsius, deduct 32, then multiply by 5, then divide by 9.
Output:
1 2 3 |
Enter a temperature in Fahrenheit: 65 Temperature: 65 Fahrenheit = 18.333333333333332 C |
Question:
Write a python program to convert KPH to MPH
Program:
1 2 3 |
kmh = int(raw_input("Enter km/h: ")) mph = 0.6214 * kmh print "Speed:", kmh, "KM/H = ", mph, "MPH" |
Explanation:
To convert KPH to MPH, just multiply by 0.6214
Output:
1 2 |
Enter km/h: 25 Speed: 25 KM/H = 15.534999999999998 MPH |