Question:
Write a program implementing basic graphic functionalities such as draw,getMouse, circle etc
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 |
from graphics import * win = GraphWin() #win is an instance of a window to display graphics content pt= Point(100,100) #pt is an object which is a Point on the screen and its co-ordinates on screen is (100,50) pt.draw(win) #the Point object pt is displayed on the screen win.getMouse() #listens for mouse click inside the window to proceed to next statement execution e = Circle(pt, 50) #e is a Circle object with centre as a Point object pt and radius 5 e.setFill('yellow') #fills blue color in the Circle object e e.draw(win) #displays the circle object win.getMouse() win.close() #closes the current GraphWin window |
Explanation:
Graphic Functionalities are implemented in python by importing graphics.py
Output:
Question:
Write a Program to encrypt text by replacing each character by it’s successor.
Program:
|
1 2 3 4 5 6 7 8 9 |
plain_text = "GlobalSQA" encrypted_text = "" for c in plain_text: x = ord(c) x = x + 1 c2 = chr(x) encrypted_text = encrypted_text + c2 print(encrypted_text) |
|
1 |
HmpcbmTRB |
Question:
Using Magic Methods, overload the + operator so that length of varying units can be added.
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 31 |
class Length: __metric = {"mm" : 0.001, "cm" : 0.01, "m" : 1, "km" : 1000, "in" : 0.0254, "ft" : 0.3048, "yd" : 0.9144, "mi" : 1609.344 } def __init__(self, value, unit = "m" ): self.value = value self.unit = unit def Converse2Metres(self): return self.value * Length.__metric[self.unit] def __add__(self, other): l = self.Converse2Metres() + other.Converse2Metres() return Length(l / Length.__metric[self.unit], self.unit ) def __str__(self): return str(self.Converse2Metres()) def __repr__(self): return "Length(" + str(self.value) + ", '" + self.unit + "')" if __name__ == "__main__": x = Length(4) print(x) y = eval(repr(x)) z = Length(7.9, "yd") + Length(2) print(repr(z)) print(z) |
Explanation:
What are magic methods? They’re everything in object-oriented Python. They’re special methods that you can define to add “magic” to your classes, that is you won’t have to call them manually. They are called automatically behind the scenes.
Output:
|
1 2 3 |
4 Length(10.0872265967, 'yd') 9.22376 |
Question:
Write a python program to find sum of natural numbers using recursion
Program:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
# Python program to find the sum of natural numbers up to n using recursive function def rsum(n): if n <= 1: return n else: return n + rsum(n-1) num = int(input("Enter a number: ")) if num < 0: print("Enter a positive number") else: print("The sum is",rsum(num)) |
Explanation:
A recursive function (DEF) is a function which either calls itself or is in a potential cycle of function calls.
Output:
|
1 |
('The sum is', 15) |
Question:
Write a python program to find ASCII character of a variable
Program:
|
1 2 3 |
c = input("Enter a character: ") print("The ASCII value of '" + c + "' is",ord(c)) |
Explanation:
ASCII (American Standard Code for Information Interchange) is the most common format for text files in computers and on the Internet. In an ASCII file, each alphabetic, numeric, or special character is represented with a 7-bit binary number (a string of seven 0s or 1s). 128 possible characters are defined.
Output:
|
1 2 |
Enter a character: H ("The ASCII value of 'H' is", 72) |
Question:
Use anonymous and filter functions and print a list of numbers divisible by 13 from the list [79, 65, 54, 39, 555, 339,623,]
Program:
|
1 2 3 4 5 6 7 |
my_list = [79, 65, 54, 39, 555, 339,623,] # use anonymous function to filter result = list(filter(lambda x: (x % 13 == 0), my_list)) # display the result print "Numbers divisible by 13 are",result |
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. Lambda functions are mainly used in combination with the functions filter(), map() and reduce().
Output:
|
1 |
Numbers divisible by 13 are [65, 39] |
Question:
Write a iterator function to work like xrange()
Program:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
class yrange: def __init__(self, n): self.i = 0 self.n = n def __iter__(self): return self def next(self): if self.i < self.n: i = self.i self.i += 1 return i else: raise StopIteration() print list(yrange(input("Enter the number:"))) |
Explanation:
The iterator protocol consists of two methods. The __iter__() method, which must return the iterator object and the next() method, which returns the next element from a sequence. Python has several built-in objects, which implement the iterator protocol. For example lists, tuples, strings, dictionaries or files.
Output:
|
1 2 |
Enter the number:3 [0, 1, 2] |
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 |