Python Programming Examples
Python Programming Examples
Python Programming Examples
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. Hint: Consider use range(#begin, #end) method
Solution:
l=[]
for i in range(2000, 3201):
if (i%7==0) and (i%5!=0):
l.append(str(i))
print ','.join(l)
Question 2:
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. Suppose the following input is supplied to the program: 8
Then, the output should be: 40320 Hint: In case of input data being supplied to the question, it should be
assumed to be a console input.
Solution:
def fact(x):
if x == 0:
return 1
return x * fact(x - 1)
x=int(raw_input())
print fact(x)
Question 3:
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. Suppose
the following input is supplied to the program: 8
Then, the output should be:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64}, Hints: In case of input data being supplied to the question, it
should be assumed to be a console input. use dict()
Solution:
n=int(raw_input())
d=dict()
for i in range(1,n+1):
d[i]=i*i
print d
Question 4:
Write a program which accepts a sequence of comma-separated numbers from console and generate a list and
a tuple which contains every number.
Page 1
Python Application Programming - Examples 2018
Solution:
values=raw_input()
l=values.split(",")
t=tuple(l)
print l
print t
Question 5:
Define a class which has at least two methods:
getString: to get a string from console input
printString: to print the string in upper case.
Also please include simple test function to test the class methods.
Hints:
Use __init__ method to construct some parameters
Solution:
class InputOutString(object):
def __init__(self):
self.s = ""
def getString(self):
self.s = raw_input()
def printString(self):
print self.s.upper()
strObj = InputOutString()
strObj.getString()
strObj.printString()
Question 6:
Write a program that calculates and prints the value according to the given formula:
Q = Square root of [(2 * C * D)/H]
Following are the fixed values of C and H:
C is 50. H is 30.
D is the variable whose values should be input to your program in a comma-separated sequence.
Page 2
Python Application Programming - Examples 2018
Example
Let us assume the following comma separated input sequence is given to the program:
100,150,180
The output of the program should be:
18,22,24
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)
In case of input data being supplied to the question, it should be assumed to be a console input.
Solution:
#!/usr/bin/env python
import math
c=50
h=30
value = []
items=[x for x in raw_input().split(',')]
for d in items:
value.append(str(int(round(math.sqrt(2*c*float(d)/h)))))
print ','.join(value)
Question 7:
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.
Example
Suppose the following inputs are given to the program:
3,5
Then, the output of the program should be:
[[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]]
Hints:
Note: In case of input data being supplied to the question, it should be assumed to be a console input in
a comma-separated form.
Solution:
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)]
Page 3
Python Application Programming - Examples 2018
print multilist
Question 8:
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.
Suppose the following input is supplied to the program:
without,hello,bag,world
Then, the output should be:
bag,hello,without,world
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
Solution:
items=[x for x in raw_input().split(',')]
items.sort()
print ','.join(items)
Question 9:
Write a program that accepts sequence of lines as input and prints the lines after making all characters in
the sentence capitalized.
Suppose the following input is supplied to the program:
Hello world
Practice makes perfect
Then, the output should be:
HELLO WORLD
PRACTICE MAKES PERFECT
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
Solution:
lines = []
while True:
s = raw_input()
if s:
lines.append(s.upper())
else:
break;
Page 4
Python Application Programming - Examples 2018
Question 10:
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.
Suppose the following input is supplied to the program:
hello world and practice makes perfect and hello world
again Then, the output should be:
again and hello makes perfect practice world
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
We use set container to remove duplicated data automatically and then use sorted() to sort the data.
Solution:
s = raw_input()
words = [word for word in s.split(" ")]
print " ".join(sorted(list(set(words))))
Question 11:
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.
Example:
0100,0011,1010,1001
Then the output should be:
1010
Notes: Assume the data is input by console.
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
Solution:
value = []
items=[x for x in raw_input().split(',')]
for p in items:
intp = int(p, 2)
if not intp%5:
value.append(p)
print ','.join(value)
Question 12:
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.
Page 5
Python Application Programming - Examples 2018
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
Solution:
values = []
for i in range(1000, 3001):
s = str(i)
if (int(s[0])%2==0) and (int(s[1])%2==0) and (int(s[2])%2==0) and (int(s[3])%2==0):
values.append(s)
print ",".join(values)
Question 13:
Write a program that accepts a sentence and calculate the number of letters and digits.
Suppose the following input is supplied to the program:
hello world! 123
Then, the output should be:
LETTERS 10
DIGITS 3
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
Solution:
s = raw_input()
d={"DIGITS":0, "LETTERS":0}
for c in s:
if c.isdigit():
d["DIGITS"]+=1
elif c.isalpha():
d["LETTERS"]+=1
else:
pass
print "LETTERS", d["LETTERS"]
print "DIGITS", d["DIGITS"]
Question 14:
Write a program that accepts a sentence and calculate the number of upper case letters and lower case letters.
Suppose the following input is supplied to the program:
Hello world!
Then, the output should be:
UPPER CASE 1
LOWER CASE 9
Hints:
Page 6
Python Application Programming - Examples 2018
In case of input data being supplied to the question, it should be assumed to be a console input.
Solution:
s = raw_input()
d={"UPPER CASE":0, "LOWER CASE":0}
for c in s:
if c.isupper():
d["UPPER CASE"]+=1
elif c.islower():
d["LOWER CASE"]+=1
else:
pass
print "UPPER CASE", d["UPPER CASE"]
print "LOWER CASE", d["LOWER CASE"]
Question 15:
Write a program that computes the value of a+aa+aaa+aaaa with a given digit as the value of a.
Suppose the following input is supplied to the program:
9
Then, the output should be:
11106
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
Solution:
a = raw_input()
n1 = int( "%s" % a )
n2 = int( "%s%s" % (a,a) )
n3 = int( "%s%s%s" % (a,a,a) )
n4 = int( "%s%s%s%s" % (a,a,a,a) )
print n1+n2+n3+n4
Question 16:
Use a list comprehension to square each odd number in a list. The list is input by a sequence of comma-
separated numbers.
Suppose the following input is supplied to the program:
1,2,3,4,5,6,7,8,9
Then, the output should be:
1,3,5,7,9
Hints: In case of input data being supplied to the question, it should be assumed to be a console input.
Solution:
values = raw_input()
numbers = [x for x in values.split(",") if int(x)%2!=0]
print ",".join(numbers)
Page 7
Python Application Programming - Examples 2018
Question 17:
Write a program that computes the net amount of a bank account based a transaction log from console input.
The transaction log format is shown as following:
D 100
W 200
¡-
D means deposit while W means withdrawal.
Suppose the following input is supplied to the
program: D 300
D 300
W 200
D 100
Then, the output should be:
500
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
Solution:
import sys
netAmount = 0
while True:
s = raw_input()
if not s:
break
values = s.split(" ")
operation = values[0]
amount = int(values[1])
if operation=="D":
netAmount+=amount
elif operation=="W":
netAmount-=amount
else:
pass
print netAmount
Question 18:
A website requires the users to input username and password to register. Write a program to check the validity
of password input by users.
Following are the criteria for checking the password:
1. At least 1 letter between [a-z]
2. At least 1 number between [0-9]
1. At least 1 letter between [A-Z]
3. At least 1 character from [$#@]
Page 8
Python Application Programming - Examples 2018
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
Solution:
import re
value = []
items=[x for x in raw_input().split(',')]
for p in items:
if len(p)<6 or len(p)>12:
continue
else:
pass
if not re.search("[a-z]",p):
continue
elif not re.search("[0-9]",p):
continue
elif not re.search("[A-Z]",p):
continue
elif not re.search("[$#@]",p):
continue
elif re.search("\s",p):
continue
else:
pass
value.append(p)
print ",".join(value)
Question 19:
You are required to write a program to sort the (name, age, height) tuples by ascending order where name is
string, age and height are numbers. The tuples are input by console. The sort criteria is:
1: Sort based on name;
2: Then sort based on age;
3: Then sort by score.
The priority is that name > age > score.
If the following tuples are given as input to the program:
Page 9
Python Application Programming - Examples 2018
Tom,19,80
John,20,90
Jony,17,91
Jony,17,93
Json,21,85
Then, the output of the program should be:
[('John', '20', '90'), ('Jony', '17', '91'), ('Jony', '17', '93'), ('Json', '21', '85'), ('Tom', '19', '80')]
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
We use itemgetter to enable multiple sort keys.
Solutions:
from operator import itemgetter, attrgetter
l = []
while True:
s = raw_input()
if not s:
break
l.append(tuple(s.split(",")))
Question 20:
Define a class with a generator which can iterate the numbers, which are divisible by 7, between a given range
0 and n. Hints: Consider use yield
Solution:
def putNumbers(n):
i=0
while i<n:
j=i
i=i+1
if j%7==0:
yield j
for i in reverse(100):
print i
Question 21:
Write a program to compute the frequency of the words from the input. The output should output after sorting
the key alphanumerically.
Suppose the following input is supplied to the program:
Page 10
Python Application Programming - Examples 2018
New to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3.
Then, the output should be:
2:2
3.:1
3?:1
New:1
Python:5
Read:1
and:1
between:1
choosing:1
or:2
to:1
Hints
In case of input data being supplied to the question, it should be assumed to be a console input.
Solution:
freq = {} # frequency of words in text
line = raw_input()
for word in line.split():
freq[word] = freq.get(word,0)+1
words = freq.keys()
words.sort()
for w in words:
print "%s:%d" % (w,freq[w])
Question 22:
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].
Hints:
Use filter() to filter some elements in a list.
Use lambda to define anonymous functions.
Solution
li = [1,2,3,4,5,6,7,8,9,10]
evenNumbers = filter(lambda x: x%2==0, li)
print evenNumbers
Question 23:
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]. Hints: Use map() to generate a list. Use lambda to define anonymous functions.
Page 11
Python Application Programming - Examples 2018
Solution
li = [1,2,3,4,5,6,7,8,9,10]
squaredNumbers = map(lambda x: x**2, li)
print squaredNumbers
Question 24:
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]. Hints:Use map() to generate a list. Use filter() to filter elements of a list. Use
lambda to define anonymous functions.
Solution
li = [1,2,3,4,5,6,7,8,9,10]
evenNumbers = map(lambda x: x**2, filter(lambda x: x%2==0, li))
print evenNumbers
Question 25:
Define a class named Circle which can be constructed by a radius. The Circle class has a method which
can compute the area. Hints: Use def methodName(self) to define a method.
Solution:
class Circle(object):
def __init__(self, r):
self.radius = r
def area(self):
return self.radius**2*3.14
aCircle = Circle(2)
print aCircle.area()
Question 26:
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. Hints: Use def methodName(self) to define a method.
Solution:
class Rectangle(object):
def __init__(self, l, w):
self.length = l
self.width = w
def area(self):
return self.length*self.width
Question 27:
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
Page 12
Python Application Programming - Examples 2018
is 0 by default. Hints: To override a method in super class, we can define a method with the same name in the
super class.
Solution:
class Shape(object):
def __init__(self):
pass
def area(self):
return 0
class Square(Shape):
def __init__(self, l):
Shape.__init__(self)
self.length = l
def area(self):
return self.length*self.length
aSquare= Square(3)
print aSquare.area()
aRectangle = Rectangle(2,10)
print aRectangle.area()
Question 28:
Write a function to compute 5/0 and use try/except to catch the exceptions.
Hints: Use try/except to catch exceptions. Solution:
def throws():
return 5/0
try:
throws()
except ZeroDivisionError:
print "division by zero!"
except Exception, err:
print 'Caught an exception'
finally:
print 'In finally block for cleanup'
Question 29:
Page 13
Python Application Programming - Examples 2018
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.
Example:
If the following email address is given as input to the program:
john@google.com
Then, the output of the program should be:
john
In case of input data being supplied to the question, it should be assumed to be a console input.
Solution:
import re
emailAddress = raw_input()
pat2 = "(\w+)@((\w+\.)+(com))"
r2 = re.match(pat2,emailAddress)
print r2.group(1)
Question 30:
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.
Example:
If the following email address is given as input to the program:
john@google.com
Then, the output of the program should be:
google
In case of input data being supplied to the question, it should be assumed to be a console input.
Hints:
Use \w to match letters.
Solution:
import re
emailAddress = raw_input()
pat2 = "(\w+)@(\w+)\.(com)"
r2 = re.match(pat2,emailAddress)
print r2.group(2)
Question 31:
Write a program which accepts a sequence of words separated by whitespace as input to print the
words composed of digits only.
Example:
Page 14
Python Application Programming - Examples 2018
Solution:
import re
s = raw_input()
print re.findall("\d+",s)
Question 32:
Write a program to compute 1/2+2/3+3/4+...+n/n+1 with a given n input by console (n>0).
Example:
If the following n is given as input to the program:
5
Then, the output of the program should be:
3.55
In case of input data being supplied to the question, it should be assumed to be a console input.
Question 33:
The Fibonacci Sequence is computed based on the following formula:
f(n)=0 if n=0
f(n)=1 if n=1
f(n)=f(n-1)+f(n-2) if n>1
Please write a program using list comprehension to print the Fibonacci Sequence in comma separated form
with a given n input by console.
Example:
If the following n is given as input to the program:
7
Then, the output of the program should be:
0,1,1,2,3,5,8,13
Hints:
We can define recursive function in Python. Use list comprehension to generate a list from an existing list.
Use string.join() to join a list of strings. In case of input data being supplied to the question, it should be
assumed to be a console input.
Page 15
Python Application Programming - Examples 2018
Solution:
def f(n):
if n == 0: return 0
elif n == 1: return 1
else: return f(n-1)+f(n-2)
n=int(raw_input())
values = [str(f(x)) for x in range(0, n+1)]
print ",".join(values)
Question 34:
Write a binary search function which searches an item in a sorted list. The function should return the index of
element to be searched in the list.
Hints:Use if/elif to deal with conditions.
Solution:
import math
def bin_search(li, element):
bottom = 0
top = len(li)-1
index = -1
while top>=bottom and index==-1:
mid = int(math.floor((top+bottom)/2.0))
if li[mid]==element:
index = mid
elif li[mid]>element:
top = mid-1
else:
bottom = mid+1
return index
li=[2,5,7,9,11,17,222]
print bin_search(li,11)
print bin_search(li,12)
Question 35:
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"].
Hints:
Use list[index] notation to get a element from a list.
Solution:
subjects=["I", "You"]
verbs=["Play", "Love"]
objects=["Hockey","Football"]
Page 16
Python Application Programming - Examples 2018
for i in range(len(subjects)):
for j in range(len(verbs)):
for k in range(len(objects)):
sentence = "%s %s %s." % (subjects[i], verbs[j], objects[k])
print sentence
Question 36:
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.
Hints:
Use set() and "&=" to do set intersection operation.
Solution:
set1=set([1,3,6,78,35,55])
set2=set([12,24,35,24,88,120,155])
set1 &= set2
li=list(set1)
print li
Question 37:
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.
Hints:
Use set() to store a number of values without duplicate.
Solution:
def removeDuplicate( li ):
newli=[]
seen = set()
for item in li:
if item not in seen:
seen.add( item )
newli.append(item)
return newli
li=[12,24,35,24,88,120,155,88,120,155]
print removeDuplicate(li)
Question 38:
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. Hints:
Solution:
class Person(object):
Page 17
Python Application Programming - Examples 2018
aMale = Male()
aFemale= Female()
print aMale.getGender()
print aFemale.getGender()
Question 39:
Write a program which count and print the numbers of each character in a string input by console.
Example:
If the following string is given as input to the program:
abcdefgabc
Then, the output of the program should be:
a,2
c,2
b,2
e,1
d,1
g,1
f,1
Hints: Use dict to store key/value pairs. Use dict.get() method to lookup a key with default value.
Solution:
dic = {}
s=raw_input()
for s in s:
dic[s] = dic.get(s,0)+1
print '\n'.join(['%s,%s' % (k, v) for k, v in dic.items()])
Question 40:
Write a program which accepts a string from console and print it in reverse order.
Example:
If the following string is given as input to the program:
rise to vote sir
Then, the output of the program should be:
ris etov ot esir
Page 18
Python Application Programming - Examples 2018
Hints:
Use list[::-1] to iterate a list in a reverse order.
Solution:
s=raw_input()
s = s[::-1]
print s
Question 41:
Please write a program which prints all permutations of [1,2,3]
Hints:
Use itertools.permutations() to get permutations of list.
Solution:
import itertools
print list(itertools.permutations([1,2,3]))
Page 19