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 |
Question:
Write a python program to remove punctuations from a string
Program:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# define punctuation punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~''' my_str = input("Enter a string: ") # remove punctuation from the string no_pt = "" for char in my_str: if char not in punctuations: no_pt = no_pt + char # display the unpunctuated string print(no_pt) |
Explanation:
There are fourteen punctuation marks commonly used in English grammar. They are the period, question mark, exclamation point, comma, semicolon, colon, dash, hyphen, parentheses, brackets, braces, apostrophe, quotation marks, and ellipsis.
Output:
1 2 |
Enter a string: GlobalSQA!! on^ the& swing)( GlobalSQA on the swing |
Question:
Write a python program to add two matrices
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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
m=int(input("ENTER MARTIX ROW SIZE m : ")) n=int(input("ENTER MARTIX COLUMN SIZE n : ")) #initializing matrix elements as 0 X = [[0]*n for j in range(m)] Y = [[0]*n for j in range(m)] result = [[0]*n for j in range(m)] #getting input to matrix X for i in range (m): for j in range (n): print ('entry in row: ',i+1,' column: ',j+1) X[i][j] = int(input()) #printing first matrix X print "FIRST MATRIX : " for i in range (m): for j in range (n): print X[i][j],"\t", print "\n" #getting input to matrix X for i in range (m): for j in range (n): print ('entry in row: ',i+1,' column: ',j+1) Y[i][j] = int(input()) #printing second matrix Y print "SECOND MATRIX : " for i in range (m): for j in range (n): print Y[i][j],"\t", print "\n" #adding X and Y to result for i in range(len(X)): for j in range(len(X[0])): result[i][j] = X[i][j] + Y[i][j] #displaying result print "SUM OF MATRICES IS : " for i in range (m): for j in range (n): print result[i][j],"\t", print "\n" |
Explanation:
If A and B are the two matrices for addition, both of them must be of the same order.
If i and j are the index positions, then result[i][j] = A[i][j] + B[i][j]
Output:
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 |
ENTER MARTIX ROW SIZE m : 2 ENTER MARTIX COLUMN SIZE n : 2 entry in row: 1 column: 1 2 entry in row: 1 column: 2 2 entry in row: 2 column: 1 2 entry in row: 2 column: 2 2 FIRST MATRIX : 2 2 2 2 entry in row: 1 column: 1 9 entry in row: 1 column: 2 9 entry in row: 2 column: 1 9 entry in row: 2 column: 2 9 SECOND MATRIX : 9 9 9 9 SUM OF MATRICES IS : 11 11 11 11 |
Question:
Write a python program to find the HCF
Program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#Program to find the H.C.F of two input number def HCF(x, y): # choose the smaller number if x > y: small = y else: small = x for i in range(1, small+1): if((x % i == 0) and (y % i == 0)): hcf = i return hcf n1 = int(input("Enter first number: ")) n2 = int(input("Enter second number: ")) print "The H.C.F. of", n1,"and", n2,"is",HCF(n1, n2) |
Explanation:
The Highest Common Factor (H.C.F) of two (or more) numbers is the largest number that divides evenly into both numbers. In other words the H.C.F is the largest of all the common factors. The common factors or of 12 and 18 are 1, 2, 3 and 6. The largest common factor is 6, so this is the H.C.F. of 12 and 18.
Output:
1 2 3 4 5 |
Enter first number: 10 Enter second number: 5 The H.C.F. of 10 and 5 is 5 |
Question :
Write a program to find the factorial of a number using recursive function
Program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
# The recursive function def factorial(n): if n == 1: return n else: return n*factorial(n-1) # take input from the user num = int(input("Enter a number: ")) # check is the number is negative if num < 0: print "Sorry, factorial does not exist for negative numbers" elif num == 0: print "The factorial of 0 is 1" else: print "The factorial of",num,"is",factorial(num) |
Explanation:
Factorial of a number is the product of all natural numbers till that number. It does not exist for negative numbers.
For example, the factorial of 4 would be 1*2*3*4=24
A recursive function is a function that calls on itself. In the above recursive function, the function calls on itself with n-1 as argument till n becomes 1 and 1 is returned. Each time the function is called, product the corresponding n and the factorial of n-1 is returned. Hence, factorial is found.
Output:
1.
1 2 |
Enter a number: -9 Sorry, factorial does not exist for negative numbers |
1 2 |
Enter a number: 1 The factorial of 1 is 1 |
1 2 |
Enter a number: 9 The factorial of 9 is 362880 |
Question:
Write a python program to find the factors of a given number
Program:
1 2 3 4 5 6 7 8 9 10 11 12 |
# Python Program to find the factors of a number # This function takes a number and prints the factors def factors(x): print "The factors of",x,"are:" for i in range(1, x + 1): if x % i == 0: print i n = int(input("Enter a number: ")) factors(n) |
Explanation:
The factors of a number are any numbers that divide into it exactly. This includes 1 and the number itself. For example, the factors of 6 are 1, 2, 3 and 6. The factors of 8 are 1, 2, 4 and 8. For larger numbers it is sometimes easier to ‘pair’ the factors by writing them as multiplications.
Output:
1 2 3 4 5 6 7 8 9 10 11 |
Enter a number: 10 The factors of 10 are: 1 2 5 10 |
Question
Write a python program to find the largest of three numbers
Hint: Use if and elif
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 |
#Accept three numbers print "Enter the numbers for comparision" nos1 = input("Enter first number: ") nos2 = input("Enter second number: ") nos3 = input("Enter third number: ") #Comparison using if elif clauses if (nos1 > nos2) and (nos1 > nos3): large = nos1 elif (nos2 > nos1) and (nos2 > nos3): large = nos2 else: large = nos3 print "The largest number is",large |
Explanation:
Three numbers are accepted from the user ‘nos1′,’nos2′,’nos3’.
First ‘nos1’ is checked.If it is greater than both ‘nos2’ and ‘nos3’, then ‘large’ is allocated wth the value of ‘nos1’
Otherwise ‘nos2’ is checked. If it is greater than both ‘nos1’ and ‘nos2’,then ‘large’ is allocated with the value of ‘nos2’
Otherwise ‘large’ is allocated with ‘nos3’
Output:
1 2 3 4 5 6 7 8 9 |
Enter the numbers for comparision Enter first number: 89 Enter second number: 23 Enter third number: 10 The largest number is 89 |