This document can be downloaded from [Link] with most recent updates.
Notes for Python Application Programming (Open Elective - 15CS664)
Solutions for Programming Questions (15CS664 – Python)
1. Design a Python program to find the average of best two marks out of three marks
taken as input.
Solution: Logic is : Find the smallest of three numbers using min() function. Then subtract
smallest number from sum of all the 3 numbers. You will get two better marks!! Find their
average.
x=int(input("Enter m1:"))
y=int(input("Enter m2:"))
z=int(input("Enter m3:"))
smallest=min(x,y,z)
avg= (x+y+z-smallest)/2
print("Average of best two marks = ",avg)
2. A string with parentheses is well bracketed if all parentheses are matched: every
opening bracket has a matching closing bracket and vice versa. Write a Python function
wellbracketed(s) that takes a string s containing parentheses and returns True if s is well
bracketed and False otherwise. Here are some examples to show how your function
should work.
>>> wellbracketed("22)") should return False
>>> wellbracketed("(a+b)(a-b)") should return True
>>> wellbracketed("(a(b+c)-d)((e+f)") should return False
Solution: Logic is: Initialize a counter variable (here it is depth) to 0. Take a loop which
iterates on every character of input string. Each time when you encounter an opening bracket,
increment depth. When you encounter closing bracket, decrement depth. In any step, if depth
becomes negative, it indicates that a closing bracket has appeared before a matching opening
bracket. In such a situation, you can terminate the loop, because the string is not-
wellbracketed. At the end of all iterations, if depth value is zero, then the string is well-
bracketed.
def wellbracketed(s):
depth=0
for i in s:
if i=='(':
depth+=1
elif i==')':
depth-=1
if depth<0:
return False
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: chetanahegde@[Link]
This document can be downloaded from [Link] with most recent updates.
Notes for Python Application Programming (Open Elective - 15CS664)
if depth==0:
return True
else:
return False
string=input("Enter a string:")
x=wellbracketed(string)
print(x)
3. A positive integer m is a sum of squares if it can be written as k + x where k > 0, x > 0
and both k and x are perfect squares. Write a Python function sumofsquares(m) that
takes an integer m returns True if m is a sum of squares and False otherwise. Here are
some examples to show how your function should work.
>>> sumofsquares(41) should return True
>>> sumofsquares(30) should return False
>>> sumofsquares(17) should return True
Solution:
import math
def sumofsquares(m):
r=[Link]([Link](m))
for j in range(1,r+1):
for k in range(r,0,-1):
if j**2+k**2==m:
return True
return False
x=int(input(“Enter a number:”))
result=sumofsquares(x)
print(x)
4. Write a program to reverse a string.
Solution: Reverse of a string can be done using string slicing with stride = -1
s= input(“Enter a string”)
s1=s[::-1]
print(“Reverse is”, s1
5. Write a program to display all the palindrome words appearing in an input text.
Solution: Logic is – Read a string (in fact, a sentence). Write a loop which iterates on a
string word-by-word. As there will be a space between two words, if you use split() function
based on white-space, you will get one word at a time in a loop. Apply slicing on this word to
reverse. Compare original word with reversed word to check any word is palindrome. Print
only those which are palindrome.
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: chetanahegde@[Link]
This document can be downloaded from [Link] with most recent updates.
Notes for Python Application Programming (Open Elective - 15CS664)
s=input("Enter a string:")
for word in [Link](' '):
if word==word[::-1]:
print(word)
6. Write a program to list out all prime numbers between two integers m and n.
Solution: A prime number is one, which is divisible by 1 and itself. Note that, a number
cannot have a factor more than half of itself. So, we will take outer loop which ranges from
m to n, and an inner loop which ranges from 2 to half of the outer loop variable.
m=int(input("Enter m:"))
n=int(input("Enter n:"))
for i in range(m,n+1):
for j in range(2,i//2 +1):
if i%j==0:
break
else:
print(i,end='\t')
7. Write a program to count the frequency of characters in a string.
Solution: Use count() method of string class.
string=input("Enter a string:")
char=input("Enter character to be counted:")
c=[Link](char)
print(char, "has appeared",c, "times")
8. Write a Python function to get a string made of the first 2 and the last 2 chars from a
given string. If the string length is less than 2, return empty string, otherwise return
new string created.
Solution: Task can be done using slicing.
def substring(s):
if len(s)<2:
return ''
else:
sub=s[:2]+s[-2:]
return sub
s=input("Enter a string:")
s1=substring(s)
print("Extracted string is:",s1)
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: chetanahegde@[Link]
This document can be downloaded from [Link] with most recent updates.
Notes for Python Application Programming (Open Elective - 15CS664)
9. Consider a string s=“Hello how are you?”. Write a program to display this string
without spaces.
Solution: Use replace() function of string class. Replace white spaces with empty string and
print the same.
s=input("Enter a string:")
s1=[Link](' ', '')
print("String without space:",s1)
10. Write a Python program to remove the characters which have odd index values of a
given string.
Solution: Can be achieved using slicing with stride value =2
s=input("Enter a string:")
s1=s[::2]
print("String with odd indexed characters removed:",s1)
11. Write a Python program to change a given string to a new string where the first and
last chars have been exchanged.
Solution: Can be done with slicing with negative indexing.
s=input("Enter a string:")
s1=s[-1]+s[1:-1]+s[0]
print("String first and last characters swapped:",s1)
12. Write a Python program to add 'ing' at the end of a given string (length should be at
least 3). If the given string already ends with 'ing' then add 'ly' instead. If the string
length of the given string is less than 3, leave it unchanged
Sample String : 'abc' Expected Result : 'abcing'
Sample String : 'string' Expected Result : 'stringly‘
Solution: Whether string ends with ‘ing’ or not can be verified using slicing. Then based on
this check, we can add either ‘ing’ or ‘ly’.
def addprefix(s):
if len(s)<3:
return s
else:
if s[-3:]!='ing':
return s+'ing'
else:
return s+'ly'
s=input("Enter a string:")
s1=addprefix(s)
print("After adding suitable prefix:",s1)
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: chetanahegde@[Link]
This document can be downloaded from [Link] with most recent updates.
Notes for Python Application Programming (Open Elective - 15CS664)
13. Write a program to check whether a given number is palindrome or not.
Solution: Read a number. Apply modulus operator to get a remainder after dividing number
by 10. Multiply remainder by 10. Divide the number by 10 to get integral part of quotient.
Continue this procedure till original number becomes zero. You will get the reversed
number. Compare original number and reversed one to check for palindrome. (Note: if you
treat the number as string, without converting it into integer format, then you can use slicing
to reverse it!!)
x=int(input("Enter a number:"))
n=x
rev=0
while n>0:
rem=n%10
rev=rev*10+rem
n=n//10
print("Reverse number is:",rev)
if x==rev:
print(x, "is a palindrome")
else:
print(x, "is not a palindrome")
14. Write a program to perform simulation of simple calculator for basic operations like +,
-, *, /, % etc. (Hint: Read a character +, - etc as operator from the user. Perform
respective operation based on the operator. And Display the result)
def Calci(a,b,op):
if op=='+':
return a+b
elif op=='-':
return a-b
elif op=='*':
return a*b
elif op=='/':
return a/b
elif op=='%':
return a%b
else:
return "Invalid Operator"
x=int(input("Enter x:"))
y=int(input("Enter y:"))
op=input("Enter Operator:")
result=Calci(x,y,op)
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: chetanahegde@[Link]
This document can be downloaded [Link] with most recent updates.
Notes for Python Application Programming (Open Elective - 15CS664)
Solutions for Programming Questions (15CS664 – Python)
For 2nd Internals
1. Write a program to count number of lines in a file and to display the line and total
count.
Given in Notes on Files (In Section 2.3.4, page no. 3)
2. Write a program to read n number of lines from the keyboard and to write them onto a
file.
fname=input(‘Enter a file name:’)
n=int(input(‘Enter number of lines:’))
fhand=open(fname,'w')
for i in range(n):
line=input("Enter a line: ")
[Link](line+"\n")
[Link]()
3. Write a program to search and print all the lines starting with a specific word (taken as
keyboard input) in a file.
fname=input(‘Enter a file name:’)
word=input(‘Enter a word to be searched:’)
fhand=open(fname)
for line in fhand:
if [Link](word):
print(line)
[Link]()
4. Write a Python program to count number of characters, words and lines in a file
file=input("Enter a file name:")
try:
fhand=open(file)
except:
print("File not found")
exit(0)
lineCount=0
wordCount=0
charCount=0
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: chetanahegde@[Link]
This document can be downloaded [Link] with most recent updates.
Notes for Python Application Programming (Open Elective - 15CS664)
for line in fhand:
lineCount+=1
charCount+=len(line)
ls=[Link]()
wordCount+=len(ls)
print('Number of lines=',lineCount)
print('Number of words=', wordCount)
print('Number of characters=', charCount)
[Link]()
5. Write a Python program print to first 10 lines and last 10 lines in a file.
file=input("Enter a file name:")
try:
fhand=open(file)
except:
print("File not found")
exit(0)
s=[Link]() #s stores whole file contents
ls=[Link]('\n') #split s based on new-line character
print('First 10 lines are:')
for i in ls[:10]:
print(i)
print('Last 10 lines are:')
for i in ls[-10:]:
print(i)
[Link]()
6. Write a python program to read a file and write into another file.
file=input("Enter a file name:")
try:
fhand1=open(file) #source file
except:
print("File not found")
exit(0)
fhand2=open('[Link]','w')
for line in fhand1:
[Link](line)
print('File copied successfully')
[Link]()
[Link]()
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: chetanahegde@[Link]
This document can be downloaded [Link] with most recent updates.
Notes for Python Application Programming (Open Elective - 15CS664)
Note: After running above file, check your folder for '[Link]', which would
have been a copy of your source file, given as input.
7. Write a python program to create a list and print all the items in reverse index order.
>>> ls=[10, 20, -3, 45, 23]
>>> print(ls[::-1])
8. Write a Python function that takes two lists and returns True if they have at least one
common member.
def common(ls1, ls2):
flag=False
for i in ls1:
for j in ls2:
if i==j:
flag= True
break
return flag
a = [1, 2, 5, 4, 15]
b = [10, 6, 7, 5, 9]
print(common(a, b)) #prints True
a = [1, 2, 3, 4, 5]
b = [6, 7, 8, 9]
print(common(a, b)) #print False
9. Write a python function to check whether the list is Ascending order or not.
Same as Program 15
10. Write a Python function that takes two sorted lists and return merged List.
ls1=[34,1,56,102,12]
ls2=[8,34,123,-2,56,1,78]
[Link]() #if ls1 is not sorted already
[Link]() #if ls2 is not sorted already
ls3=sorted(ls1+ls2)
print(ls3)
11. Write a Python program to remove duplicates from a list
def Remove(ls):
uniqueLs = []
for num in ls:
if num not in uniqueLs:
[Link](num)
return uniqueLs
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: chetanahegde@[Link]
This document can be downloaded [Link] with most recent updates.
Notes for Python Application Programming (Open Elective - 15CS664)
ls = [2, 4, 10, 20, 5, 2, 20, 4]
print(Remove(ls))
12. Write a Python program to check a list is empty or not.
def isEmpty(ls):
if len(ls)==0:
return True
else:
return False
print(isEmpty([]))
print(isEmpty([3,10,4]))
13. Write a Python program to print all the even indexed elements.
print(ls[::2])
14. A list rotation consists of taking the last element and moving it to the front. For
instance, if we rotate the list [1,2,3,4,5], we get [5,1,2,3,4]. If we rotate it again, we get
[4,5,1,2,3]. Write a Python function rotatelist(ls,k) that takes a list ls and a positive
integer k and returns the list ls after k rotations. If k is not positive, your function
should return ls unchanged. Note that your function should not change ls itself, and
should return the rotated list. Here are some examples to show how your function
shouldwork.
>>> rotatelist([1,2,3,4,5],1) #output is [5, 1, 2, 3, 4]
>>> rotatelist([1,2,3,4,5],3) #output is [3, 4, 5, 1, 2]
>>> rotatelist([1,2,3,4,5],12) #output is [4, 5, 1, 2, 3]
Program:
def rotatelist(ls,k):
mylist=ls[:]
for i in range(0,k):
mylist=[mylist[-1]]+mylist[0:-1]
return mylist
Note: The expression mylist[-1] gives single value (last value in the list). We need to
concatenate it with mylist[0:-1] using + operator to rotate the list for once. But, +
operator can concatenate two lists, but not a single value and a list. Hence, we need to use
additional square-bracket to enclose that single value as: [mylist[-1]]
15. Define a Python function ascending(ls) that returns True if each element in its input list
is at least as big as the one before it. For empty list, it should be True. Here are some
examples to show how your function should work.
>>> ascending([]) #returns True
>>> ascending([3,3,4]) #returns True
>>> ascending([7,18,17,19]) #returns False
Program:
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: chetanahegde@[Link]
This document can be downloaded [Link] with most recent updates.
Notes for Python Application Programming (Open Elective - 15CS664)
def ascending(ls):
for i in range(len(ls)-1):
if ls[i]<=ls[i+1]:
continue
else:
return False
return True
16. Define a Python function alternating(ls) that returns True if the values in the input list
alternately go up and down (in a strict manner). For empty list, it should be True
For instance:
>>> alternating([]) #True
>>> alternating([1,3,2,3,1,5]) #True
>>> alternating([3,2,3,1,5]) #True
>>> alternating([3,2,2,1,5]) #False
>>> alternating([3,2,1,3,5]) #False
17. Write a program to count frequency of each character in an input string, using
dictionary.
Given in Notes (Section 3.2.1, Page No. 16)
18. Write a program to count frequency of words in a given file, using dictionaries. Ignore
the punctuation marks attached to the words in file and treat lowercase and uppercase
letters as the same.
Given in Notes (Section 3.2.4, Page No. 19-20)
19. Consider a dictionary with strings as keys and numbers as values. Write a program to
sort the elements of this dictionary based on keys.
Given in Notes (Section 3.3.4, Page No. 29)
(To sort in ascending order, just use [Link]()instead of [Link](reverse=True)
20. Read a string from keyboard input. Create a list containing tuples, where each tuple
represents a word in the input string and length of that string. Write a program sort the
words in descending order of their length.
Given in Notes (Section 3.3.1, Page No. 26-27)
21. Write a program to display most frequent 10 words in a text file. (Hint: use dictionary,
list and tuple)
Given in Notes (Section 3.3.5, Page No. 29-30)
22. Write a python program to input a line of text name and find the frequency of each word.
s=input("Enter a string:")
d=dict()
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: chetanahegde@[Link]
This document can be downloaded [Link] with most recent updates.
Notes for Python Application Programming (Open Elective - 15CS664)
for ch in [Link]():
d[ch]=[Link](ch,0)+1
print(d)
23. Write a python program to display value and key of a dictionary using a tuples
tel_dir={'Tom': 3491, 'Jerry':8135, 'Mickey':1253}
>>> for key, val in tel_dir.items():
print(key,val)
24. Write a python program to read first name, last name and age, create a dictionary based on
name as key and age as value.
Given in Notes (Section 3.3.6, Page No. 30)
25. Write a program to extract only email-ID’s in a text file. Use suitable regular
expression.
Given in Notes (Section 3.4.2, Page No. 36 – Refer Page 37 also for perfect RegEx!!)
26. Write a program to validate USN (both UG and PG) of VTU students. (Hint: UG USN
format: 1RN15EC001, PG USN format: 1RN15MCA01)
import re
def val_USN(s):
ug_pat='[1-4]{1}[a-zA-Z]{2}[0-9]{2}[a-zA-Z]{2}[0-9]{3}'
pg_pat='[1-4]{1}[a-zA-Z]{2}[0-9]{2}[a-zA-Z]{3}[0-9]{2}'
pat=ug_pat + '|' + pg_pat #combine two patterns using |(OR)
if [Link](pat,s):
print('valid')
else:
print('invalid')
val_USN('1rn15ec001')
val_USN('1abc034kx')
val_USN('1rn15mca01')
27. Write a program to validate a mobile number in India in the form of +91 99999 99999.
(Note the white spaces after +91 and after first 5 digits)
import re
def ph_match(s):
pat='^\+91 [0-9]{5} [0-9]{5}'
if [Link](pat,s):
print('valid phone number')
else:
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: chetanahegde@[Link]
This document can be downloaded [Link] with most recent updates.
Notes for Python Application Programming (Open Elective - 15CS664)
print('invalid phone number')
ph_match('+91 94483 01894') #valid
ph_match('83 94498 45823') #invalid
28. Write a program to extract string from a file where the string should start with only
uppercase letters and should end with a digit, and must contain a special character ^,
anywhere in-between.
import re
fname=input("Enter file name:")
try:
fhand=open(fname)
except:
print("File cannot be opened")
exit(0)
for line in fhand:
pat='^[A-Z].+\^.+[0-9]$'
line=[Link]()
x=[Link](pat,line)
if len(x)>0:
print(x)
29. Python program that matches a string that has an 'a' followed by anything, ending in 'b’
import re
s=input("Enter a string:")
x=[Link]('a.+b$', s)
print(x)
30. Python program that display lines that do not contain number in a text file.
import re
fname=input("Enter file name:")
try:
fhand=open(fname)
except:
print("File cannot be opened")
exit(0)
for line in fhand:
line=[Link]()
if [Link]('^([^0-9]*)$',line):
print(line)
By: Dr. Chetana Hegde, Associate Professor, RNS Institute of Technology, Bangalore – 98
Email: chetanahegde@[Link]