Answer Key (Effective Computer Science-12)
Answer Key (Effective Computer Science-12)
Table of Contents
Chapter 3 Functions 17
https://www.amazon.in/Effective-Computer-Science-Textbook-
Gulshan/dp/9334138556/ref=sr_1_1?crid=39L27W4Q3X8E7&dib=eyJ2IjoiMSJ9.C33Xbu6xj71F3gll9
wp3XpHvzzVRRyzHg4pY9n7YqkGkVKdDpk3FfXRgKcR41zTC_kddjvxP9MPn2H3Q1wrwkDF93u5bVy7
BRgpXfMdRexbjas0PSSH231DyicMmrowMPlFJhUc6kWgu5JRdiL2d070y12AQqsnroZZZEMemnqy5Ta
nm3Fkd7LHPXYbWs5R7Sa01s0VmQbzYVruyyuy_Ia-aJtqUf-BTidjT5ox9wLw.EFnzPxt1Lngyd-
afy8hCy3lZYRiBEBOq-
mROloAtbC4&dib_tag=se&keywords=effective+computer+science&qid=1740123285&sprefix=effec
tive+computer+science%2Caps%2C271&sr=8-1
Effective Computer Science by Gulshan Sharma 3
Chapter : 1
Python Revision Tour
Unsolved Problems
1.
Ans:
l = int(input('Enter Length : '))
b = int(input('Enter Breadth : '))
a = l * b
p = 2 * ( l + b )
print('Area = ', a)
print('Perimeter = ', p)
2.
Ans:
a = int(input('Enter 1st Nuumber : '))
b = int(input('Enter 2nd Number : '))
c = int(input('Enter 3rd Number : '))
d = int(input('Enter 4th Number : '))
e = int(input('Enter 5th Number : '))
avg = (a+b+c+d+e)/5
print('Average = ', avg)
3.
Ans:
r = int(input('Enter Radius of the Circle : '))
a = 3.14 * r * r
p = 2 * 3.14 * r
print('Area = ', a)
print('Perimeter = ', p)
4.
Ans:
n = int(input('Enter an amount of money : '))
a = n//100
n = n%100
b = n//50
n = n%50
c = n//20
n = n%20
d = n//10
n = n%10
e = n//5
n = n%5
f = n//2
n = n%2
print('100 = ',a)
print('50 = ',b)
print('20 = ',c)
print('10 = ',d)
print('5 = ',e)
print('2 = ',f)
print('1 = ',n)
Effective Computer Science by Gulshan Sharma 4
5.
Ans:
n = int(input('Enter a Number in the range of 1 to 7 : '))
a = n*100 + (n+1)*10 + (n+2)
print('Resultant Number is : ', a)
6.
Ans:
n = int(input('Enter Number of Units : '))
if n <= 100:
c = 500
elif n > 100 and n <= 200:
c = 500 + 2.5* (n-100)
elif n > 200 and n <= 300:
c = 500 + 2.5 * 100 + 4.5 * (n-200)
elif n > 300:
c = 500 + 2.5 * 100 + 4.5 * 100 + 6.5 * (n-300)
print('Total Electricity Bill is : ', c)
7.
Ans:
a = int(input('Enter Number 1 : '))
b = int(input('Enter Number 2 : '))
c = int(input('Enter Number 3 : '))
if a>b and a>c:
n = a
elif b>a and b>c:
n = b
elif c>a and c>b:
n = c
else:
n = 'All are equal'
print('Largest Number is : ', n)
8.
Ans:
a = int(input('Enter Number 1 : '))
b = int(input('Enter Number 2 : '))
c = int(input('Enter Number 3 : '))
if a > b and b > c:
print(a, b, c)
elif b > c and c > a:
print(b, c, a)
elif c > a and a > b:
print(c, a, b)
elif c > b and b > a:
print(c, b, a)
elif b > a and a > c:
print(b, a, c)
elif a > c and c > b:
print(a, c, b)
else:
print('All are equal')
9.
Ans:
print('Press 1 to display area of the circle')
print('Press 2 to display area of the rectangle')
Effective Computer Science by Gulshan Sharma 5
10.
Ans: n = input('Enter an year : ')
if n in 'AEIOUaeiou':
print('It is a vowel')
else:
print('It is not a vowel')
11.
Ans:
for n in range(1, 101):
x = 0
for i in range(1, n//2+1):
if n%i == 0:
x+=1
if x == 1:
print(n , end = ',')
12.
Ans: a = int(input('Enter a number : '))
b = int(input('Enter another number : '))
x = a
y = b
while b > 0:
r = a%b
a = b
b = r
l = x*y//a
print('HCF = ', a)
print('LCM = ', l)
13.
Ans:
n = int(input('Enter a number : '))
r = 0
while n > 0:
d = n % 10
n = n // 10
r = r * 10 + d
print('Reverse of the number = ', r)
Effective Computer Science by Gulshan Sharma 6
14.
Ans:
n = int(input('Enter a number : '))
x = y = 0
while n > 0:
d = n % 10
n = n // 10
if d % 2 == 0:
x+=d
else:
y+=d
print(y-x)
15.
Ans:
s =0
while True:
n = int(input('Enter a number : '))
if n == 0:
break
if n % 2 == 0:
s = s + n
print('Sum = ', s)
16.
Ans: n=int(input('Enter Value of n:'))
(a) x=int(input('Enter Value of x:'))
s = 0
for i in range (1, n+1):
f = 1
for j in range(i, 0, -1):
f = f * j
s = s + x**(i*2-1)/f
print('Sum = ', s)
(b)
n=int(input('Enter Value of n:'))
x=int(input('Enter Value of x:'))
s = 0
sign = 1
for i in range (1, n+1):
f = 1
for j in range(i*2-1, 0, -1):
f = f * j
s = s + sign*(x**i))/f
sign = sign * -1
print('Sum = ', s)
17.
Ans:
for i in range(1, 6): for i in range(1, 6):
for i in range(1, 6): for j in range(i-1): for j in range(5-i):
for j in range(5-i): print(' ', end=' ') print(' ', end=' ')
print(' ', end=' ') for j in range(5,i-1,-): for j in range(i,0,-1):
for j in range(1, i*2): print(j, end= ') print(j, end=' ')
print(j, end=' ') for j in range(i+1, 6): for j in range(2, i+1):
print() print(j, end=' ') print(j, end= ')
print() print()
Effective Computer Science by Gulshan Sharma 7
Ans:
for i in range(1, 6):
for i in range(5, 0, -1):
for j in range(1, i+1):
for j in range(1, i+1):
print(j, end = ' ')
print(j, end = ' ')
for j in range((5-i)*2-1):
for j in range((5-i)*2-1):
print(' ', end = ' ')
print(' ', end = ' ')
if i == 5:
if i == 5:
for j in range(i-1, 0, -1):
for j in range(i-1, 0, -1):
print(j, end = ' ')
print(j, end = ' ')
else:
else:
for j in range(i, 0, -1):
for j in range(i, 0, -1):
print(j, end = ' ')
print(j, end = ' ')
print()
print()
Python Strings
1.
Ans: a = input('Enter a string : ') a = input('Enter a string : ')
p=q=r=s=0 p=q=r=s=0
for i in a: for i in range(len(a)):
if i.isupper(): if a[i].isupper():
p+=1 p+=1
elif i.islower(): elif a[i].islower():
q+=1 q+=1
elif i.isdigit(): elif a[i].isdigit():
r+=1 r+=1
elif i.isspace(): elif a[i].isspace():
s+=1 s+=1
print('Number of upper case :', p) print('Number of upper case :', p)
print('Number of lower case :', q) print('Number of lower case :', q)
print('Number of digits :', r) print('Number of digits :', r)
print('Number of spaces :', s) print('Number of spaces :', s)
2.
Ans: a = input('Enter a string : ') a = input('Enter a string : ')
b = '' b = a[::-1]
for i in range(len(a)-1, -1, -1): print('Original String :')
b = b + a[i] print(a)
print('New String :')
print('Original String :') print(b)
print(a)
print('New String :')
print(b)
Effective Computer Science by Gulshan Sharma 8
3.
Ans:
a = input('Enter a string : ')
a = a.split()
for i in range(len(a)):
a[i] = a[i][0].upper()+a[i][1:].lower()
a = ' '.join(a)
print(a)
4.
Ans:
a = input('Enter a string : ')
b = ''
for i in range(len(a)):
if i%2==0:
b = b + a[i].upper()
else:
b = b + a[i].lower()
print('New string is :', b)
5.
Ans:
a = input('Enter a string : ') a = input('Enter a string : ')
b = '' b = ''
s = 0 s = 0
for i in a: for i in range(len(a)):
if i.isdigit(): if a[i].isdigit():
b = b + i b = b + a[i]
s = s + int(i) s = s + int(a[i])
print('Original String :') print('Original String :')
print(a) print(a)
print('Collected Digits :') print('Collected Digits :')
print(b) print(b)
print('Sum of the Digits : ', s) print('Sum of the Digits : ', s)
6.
Ans: a = input('Enter a string : ') a = input('Enter a string : ')
b = input('Enter a word : ') b = input('Enter a word : ')
c = a.split() c = a.split()
x = 0 x = 0
for i in c: for i in range(len(c)):
if i == b: if c[i] == b:
x+=1 x+=1
print(b, 'appeared', x, 'times') print(b, 'appeared', x, 'times')
7.
Ans:
a = input('Enter a string : ') a = input('Enter a string : ')
b = a.split() b = a.split()
print('Original String :') print('Original String :')
print(a) print(a)
print('Words and number of vowels:') print('Words not having any vowel :')
for i in b: for i in range(len(b)):
x = 0 x = 0
for j in i: for j in range(len(b[i])):
if j in 'AEIOUaeiou': if b[i][j] in 'AEIOUaeiou':
x+=1 x+=1
print(i, x, sep = ', ') print(b[i], x, sep = ', ')
Effective Computer Science by Gulshan Sharma 9
8.
Ans:
a = input('Enter a string : ') a = input('Enter a string : ')
b = a.split() b = a.split()
print('Original String :') print('Original String :')
print(a) print(a)
print('Words starts with uppercase :') print('Words starts with uppercase :')
x = 0 x = 0
for i in b: for i in range(len(b)):
if i[0] in ‘AEIOUaeiou’ if b[i][0] in ‘AEIOUaeiou’:
print(i, end = ' ') print(b[i], end = ' ')
9.
Ans:
a = input('Enter a string : ') a = input('Enter a string : ')
b = a.split() b = a.split()
print('Original String :') print('Original String :')
print(a) print(a)
print('Words starts with uppercase :') print('Words starts with uppercase :')
x = 0 x = 0
for i in b: for i in range(len(b)):
if i[-1] in ‘AEIOUaeiou’ if b[i][-1] in ‘AEIOUaeiou’:
print(i, end = ' ') print(b[i], end = ' ')
10.
Ans:
a = input('Enter a string : ')
b = a.split()
print('Original String :')
print(a)
b.sort()
b = ' '.join(b)
print('Output String :')
print(b)
Python Tuples
1.
Ans:
a = ()
for i in range(5):
n = int(input('Enter a number : '))
a = a + (n**n,)
print('Output Tuple :')
print(a)
2.
Ans:
n=int(input('Enter number of elements:'))
a = ()
for i in range(n):
ele=int(input('Enter an integer: '))
a = a + (ele,)
print('Original Tuple :')
print(a)
Effective Computer Science by Gulshan Sharma 10
L = a[0]
S = a[0]
for i in range(1, len(a)):
if a[i] > L:
L = a[i]
for i in range(1, len(a)):
if a[i] > S and a[i] < L:
S = a[i]
print('Largest element of the Tuple :', L)
print('Second Largest element of the Tuple :', S)
3.
Ans: n = int(input('Enter number of terms : '))
a = (0, 1)
for i in range(n-2):
a = a + (a[i]+a[i+1],)
print(a)
4.
Ans: n=int(input('Enter number of elements:'))
a = ()
for i in range(n):
ele=int(input('Enter an element : '))
a = a + (ele,)
print('Original Tuple :')
print(a)
b = ()
for i in a:
c = a.count(i)
if c == 1:
b = b + (i,)
print('Output Tuple :')
print(b)
5.
Ans: a = ()
for i in range(1, 27):
a = a + (chr(96+i)*i,)
print(a)
Python Lists
1.
Ans: n= int(input('Enter size of the List : '))
a = []
print('Enter Elements in the List : ')
for i in range(n):
ele = int(input('Enter an Element : '))
a.append(ele)
print('Given List is : ', a)
for i in range(len(a)):
if a[i]%5 == 0:
a[i] = a[i]//5
else:
a[i] = a[i]*5
print('Output List is : ', a)
Effective Computer Science by Gulshan Sharma 11
2.
Ans:
n= int(input('Enter size of the List : '))
a = []
print('Enter Elements in the List : ')
for i in range(n):
ele = int(input('Enter an Element : '))
a.append(ele)
for i in range(len(a)):
if a[i]%10 == 0:
a[i] = 1
else:
a[i] = 0
3.
Ans:
n= int(input('Enter size of the List : '))
a = []
print('Enter Elements in the List : ')
for i in range(n):
ele = int(input('Enter an Element : '))
a.append(ele)
if n%2 == 0:
n = n-1
for i in range(n):
if i%2 != 0:
a[i] = a[i] + a[i+1]
else:
a[i] = a[i] + 1
4.
Ans:
n= int(input('Enter size of the List : '))
a = []
print('Enter Elements in the List : ')
for i in range(n):
ele = int(input('Enter an Element : '))
a.append(ele)
for i in range(len(a)):
if a[i]>=10 and a[i]<=99:
print(a[i])
Effective Computer Science by Gulshan Sharma 12
5.
Ans:
n= int(input('Enter size of the List : '))
a = []
print('Enter Elements in the List : ')
for i in range(n):
ele = int(input('Enter an Element : '))
a.append(ele)
print('Given List is : ', a)
s = t = 0
for i in range(len(a)):
if a[i]%2 == 0:
s = s + a[i]
else:
t = t + a[i]
print('Sum of even elements = ', s)
print('Sum of odd elements = ', t)
6.
Ans:
n = int(input('Enter size of the List : '))
a = []
print('Enter Elements in the List : ')
for i in range(n):
ele = int(input('Enter an Element : '))
a.append(ele)
print('Given List is : ', a)
for i in range(len(a)//2):
a[i], a[len(a)//2 + i] = a[len(a)//2 + i], a[i]
7.
Ans:
n = int(input('Enter size of the List : '))
a = []
print('Enter Elements in the List : ')
for i in range(n):
ele = int(input('Enter an Element : '))
a.append(ele)
print('Given List is : ', a)
for i in range(len(a)):
if i%2 == 0:
a[i], a[i-1] = a[i-1], a[i]
8.
Ans:
n = int(input('Enter size of the List : '))
a = []
print('Enter Elements in the List : ')
for i in range(n):
ele = int(input('Enter an Element : '))
a.append(ele)
Effective Computer Science by Gulshan Sharma 13
b = []
c = []
for i in range(len(a)):
if a[i]%2 == 0:
b.append(a[i])
else:
c.append(a[i])
9.
Ans:
n = int(input('Enter size of the List : '))
a = []
b = []
c = []
10.
Ans:
n = int(input('Enter size of the List : '))
a = []
print('Enter elements of the List : ')
for i in range(n):
ele = int(input('Enter an Element : '))
a.append(ele)
print('Given List is : ', a)
i = 0
while i <= len(a)-1:
if a[i]%2 == 0:
a.pop(i)
i-=1
i+=1
if len(a) == n:
print('Element not found in the List')
else:
print('List after deletion is : ', a)
Effective Computer Science by Gulshan Sharma 14
Python Dictionary
1.
Ans: n = int(input('Enter Size : '))
a = {}
for i in range(n):
k = input('Enter Name : ')
v = int(input('Enter Salary : '))
a[k] = v
for i in a:
s = s + a[i]
2.
Ans:
n = int(input('Enter Size : '))
a = {}
for i in range(n):
k = input('Enter Name : ')
v = int(input('Enter Salary : '))
a[k] = v
m = list(a.values())[0]
for i in a:
if a[i] > m:
m = a[i]
x = i
3.
Ans:
n = int(input('Enter number of students : '))
a = {}
for i in range(n):
rn = int(input('Enter Roll Number : '))
nm = input('Enter Name : ')
mk = int(input('Enter Marks : '))
a[rn] = [nm, mk]
for i in a:
if a[i][1] > 90:
print('Roll Number : ', i)
print('Name : ', a[i][0])
print('Marks : ', a[i][1])
Effective Computer Science by Gulshan Sharma 15
4.
Ans: n = int(input('Enter number of students : '))
a = {}
for i in range(n):
rn = int(input('Enter Roll Number : '))
nm = input('Enter Name : ')
mk = int(input('Enter Marks : '))
a[rn] = {'name':nm, 'marks':mk}
L = list(a.items())
L.sort(reverse=True)
print('Roll No. of Highest Scorer : ', L[0][0])
print('Name of Highest Scorer : ', L[0][1]['name'])
print('Marks of Highest Scorer : ', L[0][1]['marks'])
print('Roll No. of lowest Scorer : ', L[-1][0])
print('Name of Lowest Scorer : ', L[-1][1]['name'])
print('Marks of Lowest Scorer : ', L[-1][1]['marks'])
5.
Ans: n = int(input('Enter number of students : '))
a = {}
for i in range(n):
rn = int(input('Enter Roll Number : '))
nm = input('Enter Name : ')
mk = int(input('Enter Marks : '))
a[rn] = {'name':nm, 'marks':mk}
for i in a:
if a[i]['name'][0] == 'A' and a[i]['name'][-1] == 'e':
print('Roll No. : ', i)
print('Name : ', a[i]['name'])
print('Marks : ', a[i]['marks'])
6.
Ans: n = int(input('Enter number of students : '))
a = {}
for i in range(n):
rn = int(input('Enter Roll Number : '))
nm = input('Enter Name : ')
mk = int(input('Enter Marks : '))
a[rn] = [nm, mk]
for i in a:
if a[i][1] < 50:
a[i][1] = a[i][1] + 5
Chapter : 2
Python Modules
Unsolved Problems
1.
Ans: import math
m = int(input('Enter a number : '))
n = int(input('Enter another number : '))
print(math.pow(m, n))
2.
Ans: import math
n = float(input('Enter a number : '))
print(math.ceil(n))
3.
Ans: import math
n = float(input('Enter a number : '))
print(math.floor(n))
4.
Ans:
import random
for i in range(5):
n = random.randint(100, 200)
print(n)
5.
Ans:
import random
for i in range(5):
n = random.randrange(100, 200, 2)
print(n)
6.
Ans:
import random
for i in range(5):
n = random.randrange(1, 50, 2)
print(n)
7.
Ans:
import statistics
a = eval(input('Enter a list containing salary of employees : '))
print('Mean Value : ', statistics.mean(a))
8.
Ans:
import statistics
a = eval(input('Enter a list containing salary of employees : '))
print('Mean Value : ', statistics.mode(a))
Effective Computer Science by Gulshan Sharma 17
Chapter : 3
Functions
Unsolved Problems
1.
Ans: def Compute(p, r, t):
i = p*r*t/100
return i
2.
Ans: def Calculate(a, b, c):
if a < b and b < c:
return b
elif b < c and c < a:
return c
elif c < a and a < b:
return a
elif c < b and b < a:
return b
elif b < a and a < c:
return a
elif a < c and c < b:
return c
else:
return 'Invalid Data'
3.
Ans: def Calculate(a, b, c):
if a < b and b < c:
return a, b, c
elif b < c and c < a:
return b, c, a
elif c < a and a < b:
return c, a, b
elif c < b and b < a:
return c, b, a
elif b < a and a < c:
return b, a, c
elif a < c and c < b:
return a, c, b
else:
return 'Invalid Data'
Effective Computer Science by Gulshan Sharma 18
4.
Ans:
def Show(n):
y = n//365
n = n%365
m = n//30
n = n%30
w = n//7
n = n%7
return y, m, w, n
5.
Ans:
def CalFare(n):
if n <= 100:
a = 500
elif n > 100 and n <= 200:
a = 500 + 6 * (n-100)
elif n > 200 and n <= 300:
a = 500 + 6 * 100 + 4 * (n-200)
elif n > 300:
a = 500 + 6 * 100 + 4 * 100 + 2 * (n-300)
return a
print('Sum = ', s)
Effective Computer Science by Gulshan Sharma 19
7.
Ans:
def Check(n):
m = n
r = 0
while n > 0:
d = n % 10
n = n // 10
r = r * 10 + d
if r == m:
return 1
else:
return 0
8.
Ans:
def Calculate(a,b):
x = a
y = b
while b > 0:
r = a%b
a = b
b = r
l = x*y//a
return a, l
9.
Ans:
def Display(a):
for i in range(len(a)):
if a[i]%2 == 0:
a[i] = a[i]//2
else:
a[i] = a[i]*3
print('Output List is : ', a)
10.
Ans:
def Calculate(a):
s = 0
for i in range(len(a)):
if a[i]%2 == 0:
s = s + a[i]
return s
11.
Ans:
def Calculate(a):
s = x = 0
for i in range(len(a)):
if a[i]%5 == 0:
s = s + a[i]
x+=1
return s/x
12.
Ans:
def Maximum(a):
L = a[0]
S = a[0]
for i in range(1, len(a)):
if a[i] > L:
L = a[i]
for i in range(1, len(a)):
if a[i] > S and a[i] < L:
S = a[i]
return L, S
13.
Ans:
def stringProcess(Data):
if Data == Data[::-1]:
return 'Palindrome'
else:
return 'Not Palindrome'
14.
Ans:
def stringProcess(Data):
Data = Data.split()
n = 0
for i in Data:
for j in range(len(i)-1):
if i[j] == i[j+1]:
n+=1
break
return n
15.
Ans:
def stringProcess(Data):
Data = Data.split()
b = ''
for i in Data:
if i[0] not in 'AEIOUaeiou':
b = b + i + ' '
print(a)
stringProcess(a)
Effective Computer Science by Gulshan Sharma 22
16.
Ans:
def stringProcess(Data):
b = ''
for i in Data:
if i in 'AEIOUaeiou':
b = b + i.swapcase()
else:
b = b + i
17.
Ans:
def stringProcess(Data):
Data = Data.split()
T = ()
for i in Data:
T = T + (len(i),)
print('Output Tuple : ')
print(T)
18.
Ans:
def stringProcess(Data):
Data = Data.split()
T = ()
for i in Data:
if i[0] in 'AEIOUaeiou':
T = T + (i,)
print('Output Tuple : ')
print(T)
19.
Ans:
def stringProcess(Data):
Data = Data.split()
T = ()
for i in Data:
if len(i) > 4
T = T + (i,)
Effective Computer Science by Gulshan Sharma 23
20.
Ans:
def FibonacciSeries(n):
T = (0, 1)
for i in range(n):
T = T + (T[i]+T[i+1],)
21.
Ans:
def stringProcess(Data):
Data = Data.split()
T = ()
for i in Data:
f = False
for j in i:
if j in 'AEIOUaeiou':
f = True
if f == False:
T = T + (i,)
22.
Ans:
def stringProcess(Data):
Data = Data.split()
D = {}
for i in Data:
D[i] = len(i)
23.
Ans:
def stringProcess(Data):
Data = Data.split()
L = {}
D = {}
for i in Data:
if i not in L:
D[i] = Data.count(i)
24.
Ans:
def stringProcess(Data):
Data = Data.split()
T = ()
for i in Data:
T = T + (i[::-1],)
print(a)
stringProcess(a)
25.
Ans:
def DictProcess(a):
for i in a:
if a[i]['winning'] > a[i]['loosing']:
print('Country Name : ', i)
print('Winnings : ', a[i]['winning'])
print('Loosings : ', a[i]['loosing'])
a = {}
for i in range(n):
cn = input('Enter Country Name : ')
wi = int(input('Enter Winnings : '))
lo = int(input('Enter Loosings : '))
a[cn] = {'winning':wi, 'loosing':lo}
DictProcess(a)
Effective Computer Science by Gulshan Sharma 25
26.
Ans:
def countNow(PLACES):
for i in PLACES:
if a[i] > 5:
print('Place : ', i)
Chapter : 4
Exception Handling
Modules
Unsolved Problems
1.
Ans:
try:
a = input('Enter a string value : ')
b = int(input('Enter an integer value : '))
print(a*b)
except TypeError:
print('Invalid data is entered')
except:
print('Something went wrong')
2.
Ans:
try:
a = eval(input('Enter a Tuple : '))
for i in range(5):
print(a[i])
except IndexError:
print('Index out of range')
finally:
print('Execution of the program is over')
3.
Ans:
try:
a = int(input('Enter an integer : '))
print(a)
except ValueError:
print('Invalid Value is Entered')
finally:
print('All is done')
4.
Ans:
try:
a = input('Enter a string : ')
b = input('Enter another string : ')
print(a+b)
except ValueError:
print('Invalid Value is Entered')
except NameError:
print('Some Variables are Undefined')
except:
print('Opps! Something went wrong')
finally:
print('All is done')
Effective Computer Science by Gulshan Sharma 27
5.
Ans:
try:
a = eval(input('Enter a list of five integers : '))
for i in range(5):
a[i] = a[i]//2
print(a)
except IndexError:
print('This is not a valid index number')
except:
print('Opps! Something went wrong')
6.
Ans:
import math
try:
a = int(input('Enter a number : '))
print(math.sqrt(a))
except ImportError:
print('This module is not found')
finally:
print('All is done')
7.
Ans:
import math
try:
n = int(input('Enter size of the dictionary : '))
a = {}
for i in range(n):
nm = input('Enter Name : ')
mk = int(input('Enter Marks : '))
a[nm] = mk
x = input('Enter a Name : ')
print(a[x])
except KeyError:
print('This name is not found in the dictionary')
except:
print('Opps! Something went wrong')
Effective Computer Science by Gulshan Sharma 28
Chapter : 5
Data File Handline
2.
Ans: def show():
f = open('DATA.TXT', 'r')
a = f.read()
x = 0
for i in a:
if i.isdigit():
print(i)
f.close()
show()
3.
Ans: def show():
f = open('DATA.TXT', 'r')
a = f.read()
x = 0
for i in a:
if i.isalpha():
x+=1
print('Number of alphabets are ', x)
f.close()
show()
4.
Ans: def show():
f = open('DATA.TXT', 'r')
a = f.read()
x = 0
for i in a:
if i.isalnum():
x+=1
print('Number of alphanumeric characters are ', x)
f.close()
show()
Effective Computer Science by Gulshan Sharma 29
5.
Ans:
def show():
f = open('DATA.TXT', 'r')
a = f.read()
x = 0
for i in a:
if i not in 'aeiou':
x+=1
print('Number of characters other than lowercase vowels are ', x)
f.close()
show()
6.
Ans:
def show():
f = open('DATA.TXT', 'r')
g = open('OTHER.TXT', 'w')
a = f.read()
x = 0
for i in a:
if i in 'AEIOU':
i = '@'
elif i in 'aeiou':
i = '#'
g.write(i)
f.close()
g.close()
show()
7.
Ans:
def show():
f = open('ABC.TXT', 'r')
x = open('First.txt', 'w')
y = open('Second.txt','w')
z = open('Third.txt', 'w')
a = f.read()
x = 0
for i in a:
if i.isupper():
x.write(i)
elif i.islower():
y.write(i)
else:
x.write(i)
f.close()
x.close()
y.close()
z.close()
show()
Effective Computer Science by Gulshan Sharma 30
8.
Ans: def show():
f = open('abc.txt', 'r')
a = f.read()
for i in range(26):
x = 0
for j in a:
if j == chr(65+i) or j == chr(97+i):
x+=1
print(chr(65+i), 'or', chr(97+i), 'counted',x, 'times')
f.close()
show()
f = open('data.txt', 'r')
a = f.read()
print(a)
f.close()
show()
2.
Ans:
def show():
f = open('DATA.TXT', 'r')
a = f.read().split()
x = Y = 0
for i in a:
if i == 'Boy':
x+=1
elif i == 'Girl':
y+=1
print('Boy Counted :', x, 'times')
print('Girl Counted :', y, 'times')
f.close()
show()
3.
Ans: def show():
f = open('DATA.TXT', 'r')
a = f.read().split()
print('Number of words present in the text file are ', len(a))
f.close()
show()
Effective Computer Science by Gulshan Sharma 31
4.
Ans:
def show():
f = open('DATA.TXT', 'r')
a = f.read().split()
x = 0
for i in a:
if i[0] in 'AEIOU':
x+=1
print('Number of words starts with uppercase vowels are ',x)
f.close()
show()
5.
Ans:
def show():
f = open('DATA.TXT', 'r')
a = f.read().split()
x = 0
for i in a:
if i[0] not in 'aeiou':
x+=1
print('Number of words do not starts with lowercase vowels are ',x)
f.close()
show()
6.
Ans:
def show():
f = open('DATA.TXT', 'r')
a = f.read().split()
x = 0
for i in a:
if i[0] in 'MmPp':
x+=1
print('Number of words starts with M or P are ',x)
f.close()
show()
7.
Ans:
def show():
f = open('MyFile.txt', 'r')
g = open('data.txt','w')
a = f.read().split()
for i in a:
if i[0]=='A' and i[1]=='p' or i[0]=='B' and i[1]=='a':
print(i)
g.write(i)
f.close()
g.close()
show()
Effective Computer Science by Gulshan Sharma 32
8.
Ans: def show():
f = open('RECORD.txt', 'r')
a = f.read().split()
for i in a:
print(len(i))
f.close()
show()
9.
Ans: def show():
f = open('RECORD.txt', 'r')
a = f.read().split()
s = x = 0
for i in a:
s = s + len(i)
x==1
print('Average word size is ', s/x)
f.close()
show()
10.
Ans: def show():
f = open('DATA.TXT', 'r')
a = f.read().split()
x = 0
for i in a:
if i[-1] not in 'rt':
print(i)
x==1
print('Number of words are ', x)
f.close()
show()
11.
Ans:
def show():
f = open('DATA.TXT', 'r')
a = f.read().split()
for i in a:
i = i.title()
print(i, end = ' ')
f.close()
show()
12.
Ans:
def show():
f = open('DATA.TXT', 'r')
a = f.read().split()
for i in a:
i = i[-1]+i[1:-1]+i[0]
print(i, end = ' ')
f.close()
show()
Effective Computer Science by Gulshan Sharma 33
13.
Ans:
def show():
f = open('ABC.TXT', 'r')
g = open('XYZ.TXT', 'r')
h = open('DATA.TXT', 'w')
a = f.read().split()
b = g.read().split()
while a and b:
h.write(a[0]+b[0]+' ')
a = a[1:]
b = b[1:]
f.close()
g.close()
h.close()
show()
14.
Ans:
def show():
f = open('DATA.TXT', 'r')
a = f.read().split()
b = ''
for i in a:
if i != 'Cat':
b = b + i + ' '
f.close()
f = open('DATA.TXT', 'w')
f.write(b)
f.close()
show()
15.
Ans:
def show():
f = open('DATA.TXT', 'r')
a = f.read().split()
b = ''
for i in a:
if i == 'Cat':
b = b + 'Tiger' + ' '
else:
b = b + i + ' '
f.close()
f = open('DATA.TXT', 'w')
f.write(b)
f.close()
show()
Effective Computer Science by Gulshan Sharma 34
16.
Ans:
def show():
f = open('DATA.TXT', 'r')
a = f.read().split()
for i in a:
v = False
for j in i:
if j in 'AEIOUaeiou':
v = True
break
if v == False:
print(i)
f.close()
show()
17.
Ans: def show():
f = open('DATA.TXT', 'r')
a = f.read().split()
for i in a:
c = 0
for j in i:
if j in 'AEIOUaeiou':
c+=1
if c >= 2:
print(i)
f.close()
show()
18.
Ans: def show():
f = open('DATA.TXT', 'r')
a = f.read().split()
L = a[0]
for i in range(len(a)):
if len(a[i]) > len(L):
L = a[i]
print(L)
f.close()
show()
19.
Ans: def show():
f = open('DATA.TXT', 'r')
a = f.read().split()
a = a[::-1]
a = ' '.join(a)
f.close()
f = open('DATA.TXT', 'w')
f.write(a)
f.close()
show()
Effective Computer Science by Gulshan Sharma 35
20.
Ans:
def show():
f = open('DATA.TXT', 'r')
a = f.read().split()
for i in a:
if i == i[::-1]:
print(i)
f.close()
show()
21.
Ans:
def show():
f = open('DATA.TXT', 'r')
a = f.read().split()
for i in a:
v = False
for j in i:
if j in 'AEIOUaeiou':
v = True
break
if v == False:
print(i[::-1], end = ' ')
else:
print(i, end = ' ')
f.close()
show()
show()
2.
Ans: def show():
f = open('story.txt', 'r')
a = f.readlines()
print('First line of the file :')
print(a[0])
print('last line of the file :')
print(a[-1])
f.close()
show()
Effective Computer Science by Gulshan Sharma 36
3.
Ans:
def show():
f = open('story.txt', 'r')
g = open('other.txt','w')
a = f.readlines()
for i in a:
if i[0] == 'A' and i[1] == 'n':
print(i)
g.write(i)
f.close()
g.close()
show()
4.
Ans:
def show():
f = open('story.txt', 'r')
g = open('other.txt','w')
a = f.readlines()
for i in a:
if i[0] == 'T' and i[1] == 'h' and i[2] == 'e' and i[3] == ' ':
g.write(i)
f.close()
g.close()
show()
5.
Ans:
def show():
f = open('data.txt', 'r')
a = f.readlines()
x = 0
for i in a:
if i[0] in 'PpCc':
x+=1
print(i)
f.close()
show()
6.
Ans:
def show():
f = open('data.txt', 'r')
a = f.readlines()
for i in a:
if 'Boy' not in i and 'Girl' not in i:
print(i)
f.close()
show()
Effective Computer Science by Gulshan Sharma 37
7.
Ans: def show():
f = open('data.txt', 'r')
a = f.readlines()
for i in a:
b = i.split()
if b.count('school') > 3:
print(i)
f.close()
show()
8.
Ans: def show():
f = open('data.txt', 'r')
a = f.readlines()
L = a[0]
for i in range(len(a)):
if len(a[i]) < len(L):
L = a[i]
print(L)
f.close()
show()
9.
Ans: def show():
f = open('data.txt', 'r')
a = f.readlines()
L = ''
for i in a:
if len(i) > len(L) and 'college' not in i:
L = i
print(L)
f.close()
show()
10.
Ans: def show():
f = open('story.txt', 'r')
a = f.readlines()
for i in a:
if 'good' in i:
print(i)
f.close()
show()
11.
Ans: def show():
f = open('story.txt', 'r')
g = open('other.txt','w')
a = f.readlines()
for i in a:
if 'school' not in i:
g.write(i+'\n')
f.close()
g.close()
show()
Effective Computer Science by Gulshan Sharma 38
12.
Ans: def show():
f = open('story.txt', 'r')
a = f.readlines()
for i in a:
b = i.split()
r = True
for j in b:
if len(j) >= 5 :
r = False
if r == True:
print(i)
f.close()
show()
13.
Ans: def show():
f = open('story.txt', 'r')
a = f.read()
print('Number of Characters : ', len(a))
f.seek(0)
a = f.read().split()
print('Number of Words : ', len(a))
f.seek(0)
a = f.readlines()
print('Number of Lines : ', len(a))
f.close()
show()
writedata()
2.
Ans: import pickle
def writedata():
f = open('STU.DAT', 'wb')
for i in range(5):
a = int(input('Enter Roll Number : ')
b = input('Enter Name : ')
c = int(input('Enter Marks : '))
ob = (a, b, c)
pickle.dump(ob, f)
f.close()
writedata()
Effective Computer Science by Gulshan Sharma 39
3.
Ans: import pickle
def writedata():
f = open('REC.DAT', 'wb')
for i in range(5):
a = input('Enter Name : ')
b = int(input('Enter Salary : '))
c = input('Enter Department : ')
ob = {'name':a, 'salary':b, 'department':c}
pickle.dump(ob, f)
f.close()
writedata()
4.
Ans: import pickle
def writedata():
f = open('BOOK.DAT', 'ab')
for i in range(5):
a = int(input('Enter Book Number : ')
b = input('Enter Book Name : ')
c = int(input('Enter Price : '))
ob = {'book_no':a, 'book_name':b, 'price':c}
pickle.dump(ob, f)
f.close()
writedata()
5.
Ans: import pickle
def show():
f = open('STOCK.DAT', 'rb')
try:
while True:
ob = pickle.load(f)
if ob['item_name'] == 'SHIRT':
print(ob['item_no'])
print(ob['item_name'])
print(ob['stock'])
except EOFError:
f.close()
show()
show()
Effective Computer Science by Gulshan Sharma 41
7.
Ans: import pickle
def show():
f = open('EMP.DAT', 'rb+')
try:
while True:
p = f.tell()
ob = pickle.load(f)
ob = UPDATESAL(ob)
f.seek(p)
pickle.dump(ob, f)
except EOFError:
f.close()
show()
8.
Ans: import pickle
def show():
f = open('TOYS.DAT', 'rb')
try:
while True:
ob = pickle.load(f)
if CHECKAGE(ob) == 'valid':
print('Toy Code : ', ob[0])
print('Toy Name : ', ob[1])
print('Age Range : ', ob[2])
except EOFError:
f.close()
show()
9.
Ans: import pickle
def show():
f = open('CAMERA.DAT', 'rb')
try:
mn = input('Enter a model Number : ')
while True:
ob = pickle.load(f)
if FINDMODEL(ob, mn) == 'found':
print('Model Number : ', ob['ModelNo'])
print('Mega Pixels : ', ob['MegaPixels'])
print('Details : ', ob['Details'])
except EOFError:
f.close()
show()
10.
Ans:
import pickle
def writedata():
f = open('STUDENT.DAT', 'ab')
a = int(input('Enter ID : '))
b = input('Enter Name : ')
c = input('Enter Class : ')
d = int(input('Enter Marks : '))
ob = [a, b, c, d]
pickle.dump(ob, f)
f.close()
Effective Computer Science by Gulshan Sharma 42
Ans:
import pickle
def writedata():
f = open('STUDENT.DAT', 'rb')
try:
while True:
ob = pickle.load(f)
if ob[3]>=90 and ob[3]<=100:
print('ID :', ob[0])
print('Name :', ob[1])
print('Class :', ob[2])
print('Marks :', ob[3])
except EOFError:
f.close()
Ans:
import pickle
def writedata():
f = open('STUDENT.DAT', 'rb')
try:
x = 0
while True:
ob = pickle.load(f)
if ob[2] == 'Tenth':
x+=1
except EOFError:
f.close()
print('Number of students are ', x)
Ans:
import pickle
def writedata():
f = open('STUDENT.DAT', 'rb')
try:
nm = input('Enter a name : ')
while True:
ob = pickle.load(f)
if ob[1] == nm:
print('ID :', ob[0])
print('Name :', ob[1])
print('Class :', ob[2])
print('Marks :', ob[3])
except EOFError:
f.close()
Ans:
import pickle
def writedata():
f = open('STUDENT.DAT', 'rb')
g = open('Class.dat', 'wb')
try:
while True:
ob = pickle.load(f)
if ob[1][0] == 'P':
pickle.dump(ob, g)
except EOFError:
f.close()
g.close()
Effective Computer Science by Gulshan Sharma 43
Ans:
import pickle
def MODIFY(x):
f = open('STUDENT.DAT', 'rb+')
try:
while True:
p = f.tell()
ob = pickle.load(f)
if ob[1] == 'John':
ob[3] = ob[3] + x
f.seek(p)
pickle.dump(ob, f)
except EOFError:
f.close()
11.
Ans:
import pickle
def writedata():
f = open('COUNTRY.DAT', 'ab')
a = input('Enter Country Name : ')
b = input('Enter Capital : ')
c = int(input('Enter Population : '))
ob = {'name':a, 'capital':b, 'population':c}
pickle.dump(ob, f)
f.close()
Ans:
import pickle
def displaydata():
f = open('COUNTRY.DAT', 'rb')
try:
while True:
ob = pickle.load(f)
if ob['population'] > 500000000:
print('Country Name : ', ob['name'])
print('Capital : ', ob['capital'])
print('Population : ', ob['population'])
except EOFError:
f.close()
Ans:
import pickle
def countdata():
f = open('COUNTRY.DAT', 'rb')
try:
x = 0
while True:
ob = pickle.load(f)
if ob['name'][0] in 'AB':
x+=1
except EOFError:
f.close()
print('Number of countries : ',x)
Effective Computer Science by Gulshan Sharma 44
Ans:
import pickle
def displaydata():
f = open('COUNTRY.DAT', 'rb')
try:
nm = input('Enter a country name : ')
while True:
ob = pickle.load(f)
if ob['name'] == nm:
print('Country Name : ', ob['name'])
print('Capital : ', ob['capital'])
print('Population : ', ob['population'])
except EOFError:
f.close()
Ans:
import pickle
def copydata():
f = open('COUNTRY.DAT', 'rb')
g = open('ABC.DAT', 'wb')
try:
nm = input('Enter a country name : ')
while True:
ob = pickle.load(f)
if ob['name'][0]=='A' and ob['name'][-1]=='A':
pickle.dump(ob, g)
except EOFError:
f.close()
g.close()
Ans:
import pickle
def updatedata():
f = open('COUNTRY.DAT', 'rb+')
try:
while True:
p = f.tell()
ob = pickle.load(f)
if ob['name'] == 'India':
ob['population'] = ob['population'] + 0.05 * ob['population']
f.seek(p)
pickle.dump(ob, f)
except EOFError:
f.close()
12.
Ans: import pickle
def writedata():
f = open('SPORTS.DAT', 'wb')
for i in range(5):
a = input('Enter Country Name : ')
b = input('Enter Sports Name :')
c = int(input('Enter Number of Winnings : '))
d = int(input('Enter Number of Losings : '))
ob = [a, b, c, d]
pickle.dump(ob, f)
f.close()
Effective Computer Science by Gulshan Sharma 45
Ans:
import pickle
def displaydata():
f = open('SPORTS.DAT', 'rb')
try:
while True:
ob = pickle.load(f)
if ob[2]> ob[3]:
print('Country Name : ', ob[0])
print('Sports Name : ', ob[1])
print('Winnings : ', ob[2])
print('losings : ', ob[3])
except EOFError:
f.close()
Ans:
import pickle
def displaydata():
f = open('SPORTS.DAT', 'rb')
try:
while True:
ob = pickle.load(f)
n = ob[2]/(ob[2]+ob[3]) * 100
print('Country Name : ', ob[0])
print('Winning Percentage : ', n)
except EOFError:
f.close()
Ans:
import pickle
def displaydata():
f = open('SPORTS.DAT', 'rb')
try:
nm = input('Enter a country name : ')
while True:
ob = pickle.load(f)
if ob['name'] == nm:
print('Country Name : ', ob[0])
print('Sports Name : ', ob[1])
print('Winnings : ', ob[2])
print('losings : ', ob[3])
except EOFError:
f.close()
Ans:
import pickle
def copydata():
f = open('SPORTS.DAT', 'rb')
g = open('REC.DAT', 'wb')
try:
while True:
ob = pickle.load(f)
if ob[3] > ob[2]:
pickle.dump(ob, g)
except EOFError:
f.close()
g.close()
Effective Computer Science by Gulshan Sharma 46
Ans:
import pickle
def updatedata():
f = open('SPORTS.DAT', 'rb+')
try:
while True:
p = f.tell()
ob = pickle.load(f)
if ob[1] == 'India':
ob[2], ob[3] = ob[3], ob[2]
f.seek(p)
pickle.dump(ob, f)
except EOFError:
f.close()
1.
Ans:
import csv
def writedata():
f = open('REC.CSV', 'w', newline = '')
wob = csv.writer(f)
for i in range(5):
a = input('Enter Name : ')
b = int(input('Enter Salary : '))
c = input('Enter Department : ')
L = [a, b, c]
wob.writerow(L)
f.close()
writedata()
2.
Ans:
import csv
def writedata():
f = open('RECORDS.CSV', 'w', newline = '')
wob = csv.writer(f)
A = []
for i in range(5):
a = input('Enter Name : ')
b = int(input('Enter Salary : '))
c = input('Enter Department : ')
L = [a, b, c]
A.append(L)
wob.writerows(A)
f.close()
writedata()
Effective Computer Science by Gulshan Sharma 47
3.
Ans:
import csv
def SHOWDATA():
f = open('STUDENT.CSV', 'r')
rob = csv.reader(f)
x = 0
for i in rob:
if int(i[2])>=90 and int(i[2])<=100:
x+=1
print('Roll No. : ', i[0])
print('Name : ', i[1])
print('Marks : ', i[2])
print('Number of students are ', x)
f.close()
SHOWDATA()
4.
Ans:
import csv
def SHOWDATA():
f = open('RESULT.CSV', 'r')
x = open('EXCELLENT.CSV', 'w', newline = '')
y = open('AVERAGE.CSV', 'w', newline = '')
z = open('OTHER.CSV', 'w', newline = '')
rob = csv.reader(f)
wob1 = csv.writer(x)
wob2 = csv.writer(y)
wob3 = csv.writer(z)
for i in rob:
if int(i[2])>=80:
wob1.writerow(i)
elif int(i[2])>=50 and int(i[2])<80:
wob2.writerow(i)
else:
wob3.writerow(i)
f.close()
x.close()
y.close()
z.close()
SHOWDATA()
5.
Ans: import csv
def CALCULATE():
f = open('RESULT.CSV', 'r')
rob = csv.reader(f)
s = x = 0
for i in rob:
s = s + int(i[2])
x+=1
print('Average Marks : ', s/x)
f.close()
CALCULATE()
Effective Computer Science by Gulshan Sharma 48
6.
Ans:
import csv
def DISPLAY():
f = open('INFO.CSV', 'r')
rob = csv.reader(f)
for i in rob:
if i[2][-10:] == '@gmail.com':
print('Name : ', i[0])
print('Telephone No. : ', i[1])
print('Email Id : ', i[2])
f.close()
7.
Ans:
import csv
def DISPLAY():
f = open('STOCK.CSV', 'r')
rob = csv.reader(f)
for i in rob:
if i[1] == 'JEANS':
print('Item Number : ', i[0])
print('Item Name : ', i[1])
print('STOCK : ', i[2])
f.close()
Ans:
import csv
def COPYDATA():
f = open('STOCK.CSV', 'r')
g = open('SAVE.CSV','w', newline = '')
rob = csv.reader(f)
wob = csv.writer(g)
for i in rob:
if int(i[2])> 10 and int(i[2]<20):
wob.writerow(i)
f.close()
g.close()
8.
Ans:
import csv
def SearchMobile():
f = open('STOCK.CSV', 'r')
rob = csv.reader(f)
mn = input('Enter Model Number to be Searched : ')
for i in rob:
if FINDMOBILE(i, mn) == found:
print('Model Number :', i[0])
print('Company : ', i[1])
print('Details : ', i[2])
f.close()
Effective Computer Science by Gulshan Sharma 49
9.
Ans:
import csv
def writedata():
f = open('country.csv', 'a', newline = '')
wob = csv.writer(f)
for i in range(5):
a = input('Enter Country Name : ')
b = input('Enter Capital Name : ')
c = int(input('Enter Number of Males : '))
d = int(input('Enter Number of Females : '))
L = [a, b, c, d]
wob.writerow(L)
f.close()
writedata()
10.
Ans:
import csv
def SHOWDATA():
f = open('country.csv', 'r')
rob = csv.reader(f)
for i in rob:
if int(i[2])> int(i[3]):
print(i[0])
f.close()
11.
Ans:
import csv
def writedata():
f = open('COUNTRY.CSV', 'a', newline = '')
wob = csv.writer(f)
for i in range(5):
a = input('Enter Country Name : ')
b = input('Enter Capital Name : ')
c = int(input('Enter Population : '))
L = [a, b, c]
wob.writerow(L)
f.close()
Ans:
import csv
def SHOWDATA():
f = open('COUNTRY.CSV', 'r')
rob = csv.reader(f)
for i in rob:
if int(i[2])> 500000000:
print('Country Name : ', i[0])
print('Capital Name : ', i[1])
print('Population : ', i[2])
f.close()
Effective Computer Science by Gulshan Sharma 50
Ans:
import csv
def COUNTDATA():
f = open('COUNTRY.CSV', 'r')
rob = csv.reader(f)
x = 0
for i in rob:
if i[0][0] in 'AB':
x+=1
print('Number of records : ', x)
f.close()
Ans:
import csv
def SHOWDATA():
f = open('COUNTRY.CSV', 'r')
rob = csv.reader(f)
cn = intput('Enter Country Name to be Searched : ')
for i in rob:
if i[0] == cn:
print('Country Name : ', i[0])
print('Capital Name : ', i[1])
print('Population : ', i[2])
f.close()
Ans:
import csv
def COPYDATA():
f = open('COUNTRY.CSV', 'r')
g = open('ABC.CSV','w', newline = '')
rob = csv.reader(f)
wob = csv.writer(g)
for i in rob:
if i[0][0]=='A' and i[0][-1]=='A':
wob.writerow(i)
f.close()
g.close()
Ans:
import csv
def SHOWDATA():
f = open('COUNTRY.CSV', 'r')
rob = csv.reader(f)
s = 0
x = 0
for i in rob:
if len(i[0]) > 5:
s = s + int(i[2])
x+=1
print('Average Population : ', s/x)
f.close()
Effective Computer Science by Gulshan Sharma 51
12. a)
Ans:
import csv
def writedata():
f = open('SPORTS.CSV', 'w', newline = '')
wob = csv.writer(f)
wob.writerow(['Country Name', 'Sports Name', 'Winnings', 'Losings'])
for i in range(5):
a = input('Enter Country Name : ')
b = input('Enter Sports Name : ')
c = int(input('Enter Winnings : '))
d = int(input('Enter Losings : '))
L = [a, b, c, d]
wob.writerow(L)
f.close()
Ans:
import csv
def SHOWDATA():
f = open('SPORTS.CSV', 'r')
rob = csv.reader(f)
for i in rob:
if int(i[2]) > int(i[3]):
print('Country Name : ', i[0])
print('Sports Name : ', i[1])
print('Winnings : ', i[2])
print('Losings : ', i[3])
f.close()
Ans:
import csv
def SHOWDATA():
f = open('SPORTS.CSV', 'r')
rob = csv.reader(f)
cn = intput('Enter Country Name to be Searched : ')
for i in rob:
p = int(i[2])/(int(i[2])+int(i[3])) * 100
print('Country Name : ', i[0])
print('Winnings Percentage : ', p)
f.close()
Ans:
import csv
def SHOWDATA():
f = open('SPORTS.CSV', 'r')
rob = csv.reader(f)
cn = intput('Enter Country Name to be Searched : ')
for i in rob:
if i[0] == cn:
print('Country Name : ', i[0])
print('Sports Name : ', i[1])
print('Winnings : ', i[2])
print('Losings : ', i[3])
f.close()
Effective Computer Science by Gulshan Sharma 52
Ans:
import csv
def COPYDATA():
f = open('SPORTS.CSV', 'r')
g = open('REC.CSV','w', newline = '')
rob = csv.reader(f)
wob = csv.writer(g)
for i in rob:
if int(i[3]) > int(i[2]):
wob.writerow(i)
f.close()
g.close()
Ans:
import csv
def SHOWDATA():
f = open('SPORTS.CSV', 'r')
rob = csv.reader(f)
s = t = 0
x = y = 0
for i in rob:
if i[1] == 'Cricket':
s = s + int(i[2])
x+=1
t = t + int(i[3])
y+=1
print('Average Winnings : ', s/x)
print('Average Losings : ', t/y)
f.close()
1.
Ans: 1) STORY.TXT r
2) file.read()
3) c.isupper()
4) c.lower()
5) c.islower()
6) c.upper()
7) file.close()
8) CountChar()
2.
Ans: 1) r
2) file.read()
3) line.split()
4) len(w) < 4
5) file.close()
Effective Computer Science by Gulshan Sharma 53
3.
Ans: 1) STORY.TXT r
2) RECORD.TXT w
3) fin.readlines()
4) line[0]==’T’ and line[1]==’h’ and line[2]==’e’ and line[3]===‘’
5) fout.write(line)
4.
Ans: 1) file.seek(15)
2) PQRST
3) 20
4) file.seek(0)
5) file.read(7)
6) file.seek(-1, 2) or file.seek(file.tell()-1)
5.
Ans: 1) F = open(‘STUDENT.DAT’, ‘wb’)
2) pickle.dump(L, F)
3) R = pickle.load(F)
4) R[2] > 75
6.
Ans: 1) rb
2) try
3) load(f)
4) rec[0] == 2
5) f.close()
7.
Ans: 1) a
2) csv.writer(csvf)
3) cw.writerow([‘Title’, ‘Author’, ‘Price’]
4) csv.reader(csvf)
5) r[0][0] == ‘R’
8.
Ans: (i) (c) csv
(ii) (b) "Student.csv","w"
(iii) (c) writer(fh)
(iv) (d) roll_no,name,Class,section
(v) (c) writerows( )
9.
Ans: 1) csv
2) w
3) csv.reader
4) newFile.close()
5) Arjun 123@456
Arunima aru@nima
Frieda myname@FRD
10.
Ans: a) The
b) leg
sho
Effective Computer Science by Gulshan Sharma 54
Chapter : 6
Data Structure
2.
Ans:
def SHOW(A):
for i in range(len(A)):
if A[i]%10 == 0:
A[i] = 1
else:
A[i] = 0
print('Output List is : ', A)
3.
Ans: def SHOW(A):
for i in range(len(A)):
if A[i]%10 == 2 or A[i]%100 == 33:
print(A[i])
4.
Ans:
def SHOW(A):
S = 0
for i in range(len(A)):
S = S + A[i]
print('Sum = ', S)
5.
Ans:
def SHOW(A):
x = y = 0
for i in range(len(A)):
if A[i]%2 == 0:
x+=1
else:
y+=1
print('Number of even elements are', x)
print('Number of odd elements are', y)
6.
Ans:
def SHOW(A):
s = 0
for i in range(len(A)):
s = s + A[i]
print('Mean of the List =', s/len(A))
7.
Ans:
def SHOW(A):
s = 0
x = 0
for i in range(len(A)):
if A[i]%5 == 0:
s = s + A[i]
x+=1
print('Average =', s/x)
8.
Ans:
def SHOW(A):
s = 0
for i in range(len(A)):
if A[i]%2 != 0 and i%2 == 0:
s = s + A[i]
print('Sum = ', s)
9.
Ans:
def SHOW(A):
p = q = r = s = 0
for i in range(len(a)):
if A[i]>=0 and A[i]<=100:
p+=1
elif A[i]>=101 and A[i]<=200:
q+=1
elif A[i]>=201 and A[i]<= 300:
r+=1
else:
s+=1
print(p, q, r, s)
10.
Ans:
def SHOW(A):
for i in range(len(a)//2):
A[i], A[len(A)//2 + i] = A[len(A)//2 + i], A[i]
print('Output List is : ', A)
11.
Ans:
def SHOW(A):
for i in range(len(A)):
if i%2 == 0:
A[i], A[i+1] = A[i+1], A[i]
print('Output List is : ', A)
12.
Ans:
def SHOW(A):
for i in range(len(A)):
if A[i]%10 == 0:
A[i], A[i+1] = A[i+1], A[i]
print('Output List is : ', A)
13.
Ans:
def SHOW(A):
for i in range(len(A)):
if A[i]%5 == 0:
A[i], A[i-1] = A[i-1], A[i]
print('Output List is : ', A)
14.
Ans: def SHOW(A):
b = []
c = []
for i in range(len(A)):
if A[i]%2 == 0:
b.append(A[i])
else:
c.append(A[i])
print('Output List of even elements: ', b)
print('Output List of odd elements: ', c)
15.
Ans: def SHOW(A):
for i in range(len(A)):
x = 0
for j in range(1, A[i]+1):
if A[i]%j == 0:
x+=1
if x == 2:
print(A[i])
16.
Ans:
def SHOW(A):
b = []
c = []
for i in range(len(A)):
if A[i]%2 == 0:
b.append(A[i])
else:
c.append(A[i])
A = b+c
print('Output List : ', A)
17.
Ans:
def SHOW(A):
b = []
c = []
for i in range(len(A)):
if A[i] <0:
b.append(A[i])
else:
c.append(A[i])
A = b+c
print('Output List : ', A)
18.
Ans:
def SHOW(A):
b = []
c = []
d = []
for i in range(len(A)):
if A[i] <0:
b.append(A[i])
elif A[i] == 0:
c.append(A[i])
else:
Effective Computer Science by Gulshan Sharma 60
d.append(A[i])
A = b+c+d
print('Output List : ', A)
19.
Ans:
def SHIFT_ELEMENT(Arr, n):
Arr = Arr[-n:] + Arr[:-n]
print('Output List : ', A)
20.
Ans:
def SHIFT_ELEMENT(Arr, n):
Arr = Arr[n:] + Arr[:n]
print('Output List : ', A)
21.
Ans:
def SHOW(A):
L = A[0]
p = 0
S = A[0]
q = 0
for i in range(1, len(A)):
if A[i] > L:
L = A[i]
Effective Computer Science by Gulshan Sharma 61
p = i
elif A[i] < S:
S = A[i]
q = i
A[p], A[q] = A[q], A[p]
print('Output List : ', A)
22.
Ans:
def SHOW(A):
L = A[0]
p = 0
S = A[0]
q = 0
for i in range(1, len(A)):
if A[i] > L:
L = A[i]
p = i
elif A[i] < S:
S = A[i]
q = i
A[p] = A[p]//2
A[q] = A[p]*2
print('Output List : ', A)
23.
Ans:
def SHOW(A):
L = A[0]
p = 0
S = A[0]
q = 0
for i in range(1, len(A)):
if A[i] > L:
L = A[i]
p = i
for i in range(1, len(A)):
if A[i] > S and A[i] < L:
S = A[i]
q = i
Effective Computer Science by Gulshan Sharma 62
24.
Ans:
def SHOW(A):
L = A[0]
p = 0
S = A[0]
q = 0
for i in range(1, len(A)):
if A[i] > L:
L = A[i]
p = i
for i in range(1, len(A)):
if A[i] > S and A[i] < L:
S = A[i]
q = i
A[p], A[q] = A[q], A[p]
print('Output List : ', A)
25.
Ans:
def SHOW(A):
x = y = 0
for i in range(len(A)-1):
if A[i] <= A[i+1]:
x+=1
if A[i] >= A[i+1]:
y+=1
26.
Ans: def SHOW(A, ele):
p = None
for i in range(len(A)):
if ele <= A[i]:
p = i
break
if p == None:
A.append(ele)
else:
A.insert(p, ele)
print('List after insertion : ', A)
27.
Ans: def SHOW(A, ele):
A.insert(4, ele)
print('List after insertion : ', A)
28.
Ans:
def SHOW(A, ele, P):
A.insert(P-1, ele)
print('List after insertion : ', A)
Effective Computer Science by Gulshan Sharma 64
if len(A) == n:
print('Element not found in the List')
else:
print('List after deletion is : ', A)
30.
Ans: def SHOW(A, n):
i = 0
while i <= len(A)-1:
if A[i]%2 == 0:
A.pop(i)
i-=1
i+=1
if len(A) == n:
print('Element not found in the List')
else:
print('List after deletion is : ', A)
31.
Ans:
def SHOW(A):
i = 0
while i <= len(A)-1:
if A[i]%2 == 0:
A.pop(i)
A.insert(0,0)
i+=1
print('List after deletion is : ', A)
32.
Ans: def SHOW(A):
i = 0
x = 0
while i <= len(A)-1-x:
if A[i] < 0:
A.pop(i)
A.append(0)
x+=1
i-=1
i+=1
print('List after deletion is : ', A)
33.
Ans: def SHOW(A):
A.sort()
print('List in ascending order : ', A)
A.sort(reverse = True)
print('List in descending order : ', A)
34.
Ans: def SHOW(A,B):
C = []
for i in range(len(A)):
C.append(A[i]+B[i])
print('Output List is : ', C)
35.
Ans:
def SHOW(A,B):
c = []
d =[]
for i in range(len(A)):
if A[i]%2 == 0:
c.append(A[i])
else:
d.append(A[i])
for i in range(len(B)):
if B[i]%2 == 0:
c.append(B[i])
else:
d.append(B[i])
A = d + c
print('Output List is : ', A)
36.
Ans:
def SHOW(A):
b = []
c = []
for i in range(len(A)):
if A[i] == 0:
b.append(A[i])
else:
c.append(A[i])
A = b+c
print('Output List : ', A)
37.
Ans:
def SHOW(A, ele):
p = None
for i in range(len(A)):
if ele == A[i]:
p = i
break
if p == None:
print('Element no found in the list')
else:
print('Element found at the position ', p+1)
38.
Ans:
def SHOW(A, ele):
x = 0
for i in range(len(A)):
if ele == A[i]:
x+=1
if x== 0:
print('Element no found in the list')
else:
print('Element found',x,'times')
Effective Computer Science by Gulshan Sharma 68
39.
Ans:
def SHOW(A,B):
x = 0
for i in range(len(a)):
if a[i] in b:
x+=1
if x == len(A):
print('Both List contains same elements')
else:
print('Both List contains different elements')
SHOW(A, B)
40.
def SHOW(A,B):
x = 0
y = 0
for i in range(len(A)):
x = x + A[i]
for i in range(len(B)):
y = y + B[i]
if len(A) > len(B):
print('Extra element present in first list is', x-y)
else:
print('Extra element present in second list is', y-x)
SHOW(A, B)
41.
Ans:
def SHOW(n):
a = [0, 1]
for i in range(n-2):
a.append(a[i]+a[i+1])
print(a)
x = int(input('Enter a term number :'))
if x < len(a)-1:
print('Value = ', a[x+1])
else:
print('Term number is out of range')
42.
Ans:
def SHOW(S):
S = S.split()
a = []
for i in S:
a.append(len(i))
print('Output List : ', a)
SHOW(S)
43.
Ans:
def SHOW(S):
S = S.split()
a = []
for i in S:
if i[0] in 'AEIOUaeiou':
a.append(i)
print('Output List : ', a)
SHOW(S)
Effective Computer Science by Gulshan Sharma 70
44.
Ans:
def SHOW(S):
S = S.split()
a = []
for i in S:
if len(i) > 4:
a.append(i)
print('Output List : ', a)
45.
Ans:
def SHOW(S):
S = S.split()
a = []
for i in S:
a.append(i[::-1])
print('Output List : ', a)
46.
Ans:
def SHOW(S):
S = S.split()
a = []
for i in S:
f = 0
for j in i:
if j in 'AEIOUaeiou':
f = 1
break
if f == 0:
a.append(i)
print('Output List : ', a)
47.
Ans:
def SHOW(a):
for i in range(len(a)):
if a[i][0] in 'AaMm':
print(a[i])
48.
Ans: def SHOW(a):
for i in a:
f = 0
for j in range(len(i)-1):
if i[j] == i[j+1]:
print(i)
break
49.
Ans:
def SHOW(A):
b = []
c = []
for i in range(len(A)):
if i%2 == 0:
b.append(A[i])
else:
c.append(A[i])
print('Output List of even index elements: ', b)
print('Output List of odd index elements: ', c)
50.
Ans:
def SHOW():
a = []
for i in range(101):
a.append(i)
print(a)
SHOW()
Ans:
def SHOW():
a = []
for i in range(1, 51):
a.append(i*i)
print(a)
SHOW()
Effective Computer Science by Gulshan Sharma 72
Ans:
def SHOW():
a = []
for i in range(1, 27):
a.append(chr(64+i)*i)
print(a)
SHOW()
for i in range(m):
for j in range(n):
print(a[i][j], end = ' ')
print()
SHOW( a, m, n)
2.
Ans:
def SHOW(a, m, n):
for i in range(m):
for j in range (n):
if a[i][j] % 10 == 2 or a[i][i] % 100 == 33:
print(a[i][j])
SHOW( a, m, n)
3.
Ans:
def SHOW(a, m, n):
s = t = 0
for i in range(m):
for j in range (n):
if a[i][j]%2 == 0:
s = s + a[i][j]
else:
t = t + a[i][j]
SHOW( a, m, n)
4.
Ans:
def SHOW(a, m, n):
L = a[i][j]
S = a[i][j]
for i in range(m):
for j in range (n):
Effective Computer Science by Gulshan Sharma 74
if a[i][j] > L:
L = a[i][j]
elif a[i][j] < S:
S = a[i][j]
print('Largest elements : ', L)
print('Smallest elements : ', S)
SHOW( a, m, n)
5.
Ans:
def SHOW(a, m, n):
for i in range(m):
s = 0
for j in range (n):
if a[i][j]%2 == 0:
s = s + a[i][j]
print(s)
SHOW( a, m, n)
Effective Computer Science by Gulshan Sharma 75
6.
Ans:
def SHOW(a, m, n):
for i in range(m):
p = 1
for j in range (n):
if a[i][j]%2 != 0:
p = p * a[i][j]
print(p)
SHOW( a, m, n)
7.
Ans:
def SHOW(a, m, n):
for i in range(n):
s = 0
for j in range (m):
if a[j][i]%2 == 0:
s = s + a[j][i]
print(s)
SHOW( a, m, n)
Effective Computer Science by Gulshan Sharma 76
8.
Ans:
def SHOW(a, m, n):
for i in range(m):
L = a[i][0]
for j in range (1, n):
if a[i][j] > L:
L = a[i][j]
print(L)
SHOW( a, m, n)
9.
Ans:
def SHOW(a, m, n):
for i in range(n):
S = a[0][i]
for j in range (1, m):
if a[j][i] < S:
S = a[j][i]
print(S)
SHOW( a, m, n)
Effective Computer Science by Gulshan Sharma 77
10.
Ans:
def SHOW(a, m, n):
b = []
for i in range(m):
for j in range (n):
b.append(a[i][j])
print('Output List : ')
print(b)
SHOW( a, m, n)
11.
Ans:
def SHOW(a, m, n):
b = []
for i in range(n):
for j in range (m):
b.append(a[j][i])
print('Output List : ')
print(b)
12.
Ans:
def SHOW(a, m, n):
b = []
c = []
for i in range(m):
for j in range (n):
if a[i][j]%2 == 0:
b.append(a[i][j])
else:
c.append(a[i][j])
SHOW( a, m, n)
13.
Ans:
def SHOW(a, n):
for i in range(n):
for j in range (n):
if i+j<=n-1:
print(a[i][j], end = ' ')
else:
print(' ', end = ' ')
print()
for j in range(n):
print(a[i][j], end = ' ')
print()
print('Output Matrix :')
SHOW( a, n)
14.
Ans:
def SHOW(a, n):
for i in range(n):
for j in range (n):
if i+j>=n-1:
print(a[i][j], end = ' ')
else:
print(' ', end = ' ')
print()
15.
Ans:
def SHOW(a, n):
for i in range(n):
for j in range (n):
if i>=j:
print(a[i][j], end = ' ')
else:
print(' ', end = ' ')
print()
for j in range(n):
print(a[i][j], end = ' ')
print()
print('Output Matrix :')
SHOW( a, n)
16.
Ans:
def SHOW(a, n):
for i in range(n):
for j in range (n):
if i==n//2 or j==n//2:
print(a[i][j], end = ' ')
else:
print(' ', end = ' ')
print()
17.
Ans:
def SHOW(a, n):
for j in range (n):
if i==0 or i==n-1 or j==0 or j==n-1:
s = s + a[i][j]
print('Sum of the boundry elements of the Matrix : ')
print(s)
SHOW( a, n)
Effective Computer Science by Gulshan Sharma 81
18.
Ans:
def SHOW(a, n):
for j in range (n):
if i!=0 and i!=n-1 and j!=0 and j!=n-1:
s = s + a[i][j]
print('Sum of the boundry elements of the Matrix : ')
print(s)
SHOW( a, n)
19.
Ans:
def SHOW(a, n):
for i in range(n):
for j in range (n):
if (i==0 and j==0) or (i==n-1 and j==0) or (i==0 and j==n-1) or (i==n-1
and j==n-1):
print(a[i][j], end = ' ')
else:
print(' ', end = ' ')
print()
SHOW( a, n)
Effective Computer Science by Gulshan Sharma 82
20.
Ans: def SHOW(a, n):
for i in range(n):
for j in range (n):
if i <=j:
a[i][j], a[j][i] = a[j][i], a[i][j]
SHOW( a, n)
21.
Ans: def SHOW(a, n):
print('Elements of Second Quarter of the Matrix : ')
for i in range(n):
for j in range (n):
if i<=n//2 and j>=n//2:
print(a[i][j], end = ' ')
else:
print(' ', end = ' ')
print()
SHOW( a, n)
Effective Computer Science by Gulshan Sharma 83
22.
Ans:
def SHOW(a, n):
print('Elements of Second Quarter of the Matrix : ')
for i in range(n):
for j in range (n):
if i>=n//2 and j<=n//2:
print(a[i][j], end = ' ')
else:
print(' ', end = ' ')
print()
SHOW( a, n)
23.
Ans: def SHOW(a, n):
print('Elements of Second Quarter of the Matrix : ')
for i in range(n):
for j in range (n):
if i>=n//2 and j>=n//2:
print(a[i][j], end = ' ')
else:
print(' ', end = ' ')
print()
SHOW( a, n)
Effective Computer Science by Gulshan Sharma 84
24.
Ans:
def SHOW(a, m, n):
print('\nElements of middle row : ')
for i in range(n):
print(a[m//2][i], end = ' ')
SHOW( a, m, n)
25.
Ans: def SHOW(a, m, n):
print('\nLeft Diagnol : ')
for i in range(n):
print(a[i][i], end = ' ')
SHOW( a, m, n)
Effective Computer Science by Gulshan Sharma 85
26.
Ans: def SHOW(a, m, n):
for i in range(n):
a[m//2][i],a[i][n//2] = a[i][n//2], a[m//2][i]
27.
Ans: def SHOW(a, m, n):
for i in range(n):
a[i][i],a[i][n-1-i] = a[i][n-1-i], a[i][i]
SHOW( a, m, n)
Effective Computer Science by Gulshan Sharma 86
28.
Ans:
def SHOW(a, m, n):
for i in range(m):
a[i][0] , a[i][n-1] = a[i][n-1] , a[i][0]
SHOW( a, m, n)
29.
Ans:
def SHOW(a, x):
if a == x:
print('Both matrices are identical')
else:
print('Both matrices are not identical')
SHOW( a, x)
30.
Ans:
def SHOW(a, m, n):
for i in range(m//2):
for j in range(n):
a[i][j] , a[m-1-i][j] = a[m-1-i][j] , a[i][j]
SHOW( a, m, n)
31.
Ans:
def SHOW(a, m, n):
for i in range(n//2):
for j in range(m):
a[j][i] , a[j][n-1-i] = a[j][n-1-i] , a[j][i]
SHOW( a, m, n)
32.
Ans:
def SHOW(a, m, n):
for i in range(m):
a[i] = a[i][n//2:] + a[i][:n//2]
SHOW( a, m, n)
33.
Ans:
def SHOW(a):
b = []
for i in range(n):
c = []
for j in range(n):
Effective Computer Science by Gulshan Sharma 89
if i<=j:
c.append(a[j-i])
else:
c.append(0)
b.append(c)
SHOW( a)
34.
Ans:
def SHOW(a):
b = []
for i in range(n):
c = []
for j in range(n):
if i==0:
c.append(a[j])
elif i==n-1:
c.append(a[i-j])
elif j==0:
c.append(a[i])
elif j==n-1:
c.append(a[j-i])
else:
c.append(0)
b.append(c)
35.
Ans:
def SHOW(a, m, n):
for x in range(m):
for i in range(n-1):
for j in range(n-1-i):
if a[x][j] > a[x][j+1]:
a[x][j], a[x][j+1] = a[x][j+1], a[x][j]
SHOW( a, m, n)
36.
Ans:
def SHOW(a, m, n):
for x in range(n):
for i in range(m-1):
for j in range(m-1-i):
if a[j][x] > a[j+1][x]:
a[j][x], a[j+1][x] = a[j+1][x], a[j][x]
a.append(b)
SHOW( a, m, n)
Effective Computer Science by Gulshan Sharma 92
Chapter : 7
Stacks and Queues
Unsolved Problems
1.
Ans: stk = []
def PushData(City, stk):
for i in City:
stk.append(i)
def PopData(stk):
if stk == []:
print('Underflow')
else:
print(stk.pop())
2.
Ans: que = []
def Addnew(Member, que):
for i in Member:
que.append(i)
def Remove(que):
if que == []:
print('Underflow')
else:
print(que.pop(0))
3.
Ans:
Item = []
def PushData(Item):
Item_ID = int(input('Enter item id : '))
Item_Name = input('Enter item name : ')
Item_Price = float(input('Enter item price : '))
Company = input('Enter company name : ')
ele = [Item_ID, Item_Name, Item_Price, Company]
Item.append(ele)
def PopData(Item):
if Item == []:
print('Underflow')
else:
print(Item.pop())
4.
Ans:
Student = []
def Insertion(Student):
Roll_no = int(input('Enter roll no. : '))
Name = input('Enter name : ')
Marks = float(input('Enter marks : '))
Grade = input('Enter grade : ')
ele = [Roll_no, Name, Marks, Grade]
Item.append(ele)
Effective Computer Science by Gulshan Sharma 93
def Deletion(Student):
if Student == []:
print('Underflow')
else:
print(Student.pop(0))
5.
Ans:
package = []
def PushData(package):
Package_id = int(input('Enter package id : '))
Package_Weight = float(input('Enter item price : '))
Company = input('Enter company name : ')
ele = [Package_id, Package_Weight, Company]
package.append(ele)
def PopData(package):
if package == []:
print('Underflow')
else:
print(package.pop())
6.
Ans:
patient = []
def Insertion(patient):
Patient_Id = int(input('Enter patient id : '))
Patient_Name = input('Enter patient name : ')
Fees = float(input('Enter fees : '))
ele = [Patient_Id, Patient_Name, Fees]
patient.append(ele)
def Deletion(patient):
if patient == []:
print('Underflow')
else:
print(patient.pop(0))
7.
Ans:
STK = []
def PUSH(A, STK):
for i in A:
if i.isupper():
STK.append(i)
def POP(STK):
if STK == []:
print('Underflow')
else:
while True:
print(STK.pop(), end = ' ')
if STK == []:
print('Underflow')
break
Effective Computer Science by Gulshan Sharma 94
8.
Ans:
QUE = []
def ENQUEUE(A, QUE):
for i in A:
if i in 'AEIOUaeiou':
QUE.append(i)
def DEQUEUE(QUE):
if QUE == []:
print('Underflow')
else:
while True:
print(QUE.pop(0), end = ' ')
if QUE == []:
print('Underflow')
break
9.
Ans:
STK = []
def PUSH(A, STK):
A = A.split()
for i in A:
if i[0].isupper():
STK.append(i)
def POP(STK):
if STK == []:
print('Underflow')
else:
while True:
print(STK.pop())
if STK == []:
print('Underflow')
break
10.
Ans:
STK = []
def PUSH(A, STK):
A = A.split()
for i in A:
if i[0] in 'AEIOUaeiou':
STK.append(i)
def POP(STK):
if STK == []:
print('Underflow')
else:
while True:
print(STK.pop(), end = ' ')
if STK == []:
print('Underflow')
break
Effective Computer Science by Gulshan Sharma 95
11.
Ans:
QUE = []
def ENQUEUE(A, QUE):
A = A.split()
for i in A:
if i[-1] in 'AEIOUaeiou':
QUE.append(i)
def DEQUEUE(QUE):
if QUE == []:
print('Underflow')
else:
while True:
print(QUE.pop(0), end = ' ')
if QUE == []:
print('Underflow')
break
12.
Ans:
QUE = []
def ENQUEUE(A, QUE):
A = A.split()
for i in A:
QUE.append(len(i))
def DEQUEUE(QUE):
if QUE == []:
print('Underflow')
else:
while True:
print(QUE.pop(0), end = ', ')
if QUE == []:
print('Underflow')
break
13.
Ans:
STK = []
def PUSH(A, STK):
A = A.split()
for i in A:
STK.append(i[::-1])
def POP(STK):
if STK == []:
print('Underflow')
else:
while True:
print(STK.pop(), end = ' ')
if STK == []:
print('Underflow')
break
Effective Computer Science by Gulshan Sharma 96
14.
Ans:
QUE = []
def ENQUEUE(A, QUE):
A = A.split()
for i in A:
if i == i[::-1]:
QUE.append(i)
def DEQUEUE(QUE):
if QUE == []:
print('Underflow')
else:
while True:
print(QUE.pop(0), end = ' ')
if QUE == []:
print('Underflow')
break
15.
Ans:
STK = []
def PUSH(A, STK):
A = A.split()
for i in A:
for j in range(len(i)-1):
if i[j] == i[j+1]:
STK.append(i)
break
def POP(STK):
if STK == []:
print('Underflow')
else:
while True:
print(STK.pop())
if STK == []:
print('Underflow')
break
16.
Ans:
def Word_3_Length(STR, W3):
STR = STR.split()
for i in STR:
if len(i) == 3:
W3.append(i)
def Del_Word(W3):
if W3 == []:
print('No More Words')
else:
while True:
print(W3.pop(0), end = ' ')
if W3 == []:
print('No More Words')
break
Effective Computer Science by Gulshan Sharma 97
17.
Ans:
def No_Vowel(STR, NVW):
STR = STR.split()
for i in STR:
f = False
for j in i:
if j in 'AEIOUaeiou':
f = True
break
if f == False:
NVW.append(i)
def POP(NVW):
if NVW == []:
print('Empty Stack')
else:
while True:
print(NVW.pop(), end = ' ')
if NVW == []:
print('Empty Stack')
break
18.
Ans:
STK = []
def PUSH(A, STK):
for i in A:
if i%2 == 0:
STK.append(i)
def POP(STK):
if STK == []:
print('Underflow')
else:
while True:
print(STK.pop(), end = ‘, ’)
if STK == []:
break
19.
Ans:
QUE = []
def ENQUEUE(A, QUE):
for i in A:
if i>=10 and i<=99:
QUE.append(i)
def DEQUEUE(QUE):
if QUE == []:
print('Underflow')
else:
while True:
print(QUE.pop(0), end = ', ')
if QUE == []:
break
Effective Computer Science by Gulshan Sharma 98
20.
Ans:
STK = []
def PrimeOnly(Prime, STK):
for i in Prime:
x = 0
for j in range(1, i+1):
if i%j == 0:
x+=1
if x == 2:
STK.append(i)
def PopPrime(STK):
if STK == []:
print('Underflow')
else:
while True:
print(STK.pop(), end = ' ')
if STK == []:
print('Underflow')
break
21.
Ans:
QUE = []
def ENQUEUE(A, QUE):
for i in A:
if i%10 == 2 or i%100 == 33:
QUE.append(i)
def DEQUEUE(QUE):
if QUE == []:
print('Underflow')
else:
while True:
print(QUE.pop(0), end = ', ')
if QUE == []:
break
22.
Ans:
STK = []
def PUSH(N, STK):
for i in A:
if i[0] in 'AT':
STK.append(i)
def POP(STK):
if STK == []:
print('Empty Stack')
else:
while True:
print(STK.pop())
if STK == []:
print('Empty Stack')
break
Effective Computer Science by Gulshan Sharma 99
23.
Ans:
QUE = []
def ENQUEUE(D, QUE):
for i in D:
if D[i] > 50000:
QUE.append(i)
def DEQUEUE(QUE):
if QUE == []:
print('Underflow')
else:
while True:
print(QUE.pop(0), end = ', ')
if QUE == []:
break
24.
Ans:
STK = []
def PUSH(D, STK):
for i in D:
if i[0] == 'A':
STK.append(D[i])
def POP(STK):
if STK == []:
print('Empty Stack')
else:
while True:
print(STK.pop())
if STK == []:
break
25.
Ans:
Book = []
def PUSH(Book, N):
for i in N:
if N[i] > 500:
Book.append((i, N[i]))
def POP(Book):
if Book == []:
print('Empty Stack')
else:
while True:
print(Book.pop())
if Book == []:
break
Effective Computer Science by Gulshan Sharma 100
26.
Ans:
STK = []
def PUSH(A, STK):
for i in A:
x = 0
for j in i:
if j%2 == 0:
x+=1
if x > 2:
STK.append(i)
def POP(STK):
if STK == []:
print('Empty Stack')
else:
while True:
print(STK.pop())
if STK == []:
break
27.
Ans:
Q = []
def INSERT_QUE(A, Q):
for i in A:
s = 0
for j in i:
s = s + j
if s > 100:
Q.append(i)
def DELETE_QUE(Q):
if Q == []:
print('Empty Stack')
else:
while True:
print(Q.pop(0), end = ' , ')
if Q == []:
break
28.
Ans:
Student = []
def ENQUEUE(Student, L):
for i in L:
if i[2] > 80:
Student.append(i)
def DEQUEUE(Student):
if Student == []:
print('Empty Stack')
else:
while True:
print(Student.pop(0), end = ' , ')
if Student == []:
break
Effective Computer Science by Gulshan Sharma 101
29.
Ans:
Student = []
def PUSH_STU(Student, L):
for i in L:
if i[3] == 'A':
Student.append([i[1], i[2]])
def POP_STU(Student):
if Student == []:
print('Empty Stack')
else:
while True:
print(Student.pop())
if Student == []:
break
30.
Ans:
Book = []
def PUSH(Book, D):
for i in D:
if D[i]['price'] > 500:
Book.append(D[i])
def POP(Book):
if Book == []:
print('Empty Stack')
else:
while True:
print(Book.pop())
if Book == []:
break
31.
Ans:
City = []
def PUSH(City, D):
for i in D:
if D[i]['city'] == 'Delhi':
City.append([D[i]['areacode'], D[i]['telno']])
def POP(City):
if City == []:
print('Empty Stack')
else:
while True:
print(City.pop())
if City == []:
break
32.
Ans:
Stu = []
def PUSH(Stu, D):
for i in D:
if D[i][1] == 12:
Stu.append([D[i][0], D[i][2]])
Effective Computer Science by Gulshan Sharma 102
def POP(Stu):
if Stu == []:
print('Empty Stack')
else:
while True:
print(Stu.pop())
if Stu == []:
break
33.
Ans: Emp = []
def PUSH_EMP(Emp, L):
for i in L:
if i[3][-10:] == '@gmail.com':
Emp.append([i[1],i[2]])
def POP_EMP(Emp):
if Emp == []:
print('Empty Stack')
else:
while True:
print(Emp.pop())
if Emp == []:
break
34.
Ans: STK = []
def PUSH_EMP(STK, L):
for i in L:
if len(str(i[0])) > 4:
STK.append([i[1],i[2]])
def POP_EMP(STK):
if STK == []:
print('Empty Stack')
else:
while True:
print(STK.pop())
if STK == []:
break
35.
Ans: Stu = []
def PUSH(Stu, D):
for i in D:
if D[i][0][0] =='A' and D[i][1]%10 == 0:
Stu.append([i, D[i][0]])
def POP(Stu):
if Stu == []:
print('Empty Stack')
else:
while True:
print(Stu.pop())
if Stu == []:
break
Effective Computer Science by Gulshan Sharma 103
Chapter : 10
Interface Python With SQL Database
UnSolved Problems
1.
Ans:
import mysql.connector
conobj = mysql.connector.connect(host = "localhost", user = "root", password =
"super", database = "ORGANIZATION")
2.
Ans:
import mysql.connector
conobj = mysql.connector.connect(host = "localhost", user = "root", password =
"super", database = "ORGANIZATION")
cursor = conobj.cursor()
cursor.execute("Insert into EMPLOYEE(ID, NAME, DETARTMENT) Values (101, 'Harry
potter', 'Accounts' )")
conobj.commit()
conobj.close()
3.
Ans:
import mysql.connector
conobj = mysql.connector.connect(host = "localhost", user = "root", password =
"super", database = "ORGANIZATION")
cursor = conobj.cursor()
cursor.execute("select * from EMPLOYEE")
data = cursor.fetchall()
print(data)
print('Number of records = ', cursor.rowcount)
conobj.close()
4.
Ans:
import mysql.connector
conobj = mysql.connector.connect(host = "localhost", user = "root", password =
"super", database = "ORGANIZATION")
cursor = conobj.cursor()
cursor.execute("select * from EMPLOYEE")
data = cursor.fetchone()
x = 1
while data is not None:
print('Record Number : ', x)
print(data)
data = cursor.fetchone()
x+=1
conobj.close()
Effective Computer Science by Gulshan Sharma 104
5.
Ans:
import mysql.connector
conobj = mysql.connector.connect(host = "localhost", user = "root", password =
"super", database = "ORGANIZATION")
cursor = conobj.cursor()
cursor.execute("select * from EMPLOYEE where SALARY > 100000")
data = cursor.fetchall()
print(data)
conobj.close()
6.
Ans:
import mysql.connector
conobj = mysql.connector.connect(host = "localhost", user = "root", password =
"super", database = "ORGANIZATION")
cursor = conobj.cursor()
cursor.execute("select * from EMPLOYEE where DEPARTMENT in ('Accounts', 'Sales')")
data = cursor.fetchall()
print(data)
conobj.close()
7.
Ans:
import mysql.connector
conobj = mysql.connector.connect(host = "localhost", user = "root", password =
"super", database = "ORGANIZATION")
cursor = conobj.cursor()
a = input('Enter name of the department : ')
cursor.execute("select * from EMPLOYEE where DEPARTMENT = '{}' and SALARY between
50000 and 70000".format(a))
data = cursor.fetchall()
print(data)
conobj.close()
8.
Ans: import mysql.connector
conobj = mysql.connector.connect(host = "localhost", user = "root", password =
"super", database = "ORGANIZATION")
cursor = conobj.cursor()
a = int(input('Enter id of an employee : ')
cursor.execute("update EMPLOYEE set DEPARTMENT = 'Accounts' where ID =
{}".format(a))
conobj.commit()
conobj.close()
9.
Ans: import mysql.connector
conobj = mysql.connector.connect(host = "localhost", user = "root", password =
"super", database = "ORGANIZATION")
cursor = conobj.cursor()
a = input('Enter name of the department : ')
b = int(input('Enter salary : '))
cursor.execute("delete from EMPLOYEE where DEPARTMENT = '{}' and SALARY <
{}".format(a,b))
conobj.commit()
conobj.close()
Effective Computer Science by Gulshan Sharma 105
10.
Ans:
import mysql.connector
conobj = mysql.connector.connect(host = "localhost", user = "root", password =
"book", database = "LIBRARY")
11.
Ans:
import mysql.connector
conobj = mysql.connector.connect(host = "localhost", user = "root", password =
"book", database = "LIBRARY")
cursor = conobj.cursor()
cursor.execute("Insert into BOOK(ID, NAME, PRICE) Values (55, 'Die to Live',750)")
conobj.commit()
conobj.close()
12.
Ans:
import mysql.connector
conobj = mysql.connector.connect(host = "localhost", user = "root", password =
"book", database = "LIBRARY")
cursor = conobj.cursor()
cursor.execute("select * from BOOK where PRICE > 5000")
data = cursor.fetchall()
print(data)
print('Number of records = ', cursor.rowcount)
conobj.close()
13.
Ans:
import mysql.connector
conobj = mysql.connector.connect(host = "localhost", user = "root", password =
"book", database = "LIBRARY")
cursor = conobj.cursor()
cursor.execute("select * from BOOK")
data = cursor.fetchone()
x = 1
while data is not None:
print('Record Number : ', x)
print(data)
data = cursor.fetchone()
x+=1
conobj.close()
14.
Ans:
import mysql.connector
conobj = mysql.connector.connect(host = "localhost", user = "root", password =
"book", database = "LIBRARY")
cursor = conobj.cursor()
cursor.execute("select * from BOOK where PRICE < 500")
data = cursor.fetchall()
print(data)
conobj.close()
Effective Computer Science by Gulshan Sharma 106
15.
Ans:
import mysql.connector
conobj = mysql.connector.connect(host = "localhost", user = "root", password =
"book", database = "LIBRARY")
cursor = conobj.cursor()
a = input('Enter a book name : ')
cursor.execute("select * from BOOK where NAME = '{}'".format(a))
data = cursor.fetchall()
print(data)
conobj.close()
16.
Ans:
import mysql.connector
conobj = mysql.connector.connect(host = "localhost", user = "root", password =
"book", database = "LIBRARY")
cursor = conobj.cursor()
a = input('Enter a book name : ')
cursor.execute("select * from BOOK where ID in between 125 and 255")
data = cursor.fetchall()
print(data)
conobj.close()
17.
Ans:
import mysql.connector
conobj = mysql.connector.connect(host = "localhost", user = "root", password =
"book", database = "LIBRARY")
cursor = conobj.cursor()
a = input('Enter a book name : ')
cursor.execute("update BOOK set PRICE = 1200 where ID = 7693")
conobj.commit()
conobj.close()
18.
Ans:
import mysql.connector
conobj = mysql.connector.connect(host = "localhost", user = "root", password =
"book", database = "LIBRARY")
cursor = conobj.cursor()
a = input('Enter a book name : ')
b = int(input('Enter an amount : '))
cursor.execute("update BOOK set PRICE = PRICE + {} where NAME = '{}'".format(b,a))
conobj.commit()
conobj.close()
19.
Ans:
import mysql.connector
conobj = mysql.connector.connect(host = "localhost", user = "root", password =
"book", database = "LIBRARY")
cursor = conobj.cursor()
cursor.execute("delete form BOOK where PRICE < 200")
conobj.commit()
conobj.close()
Effective Computer Science by Gulshan Sharma 107
20.
Ans: 1) mysql.connector
2) connect(host="localhost", user="root", password="PYTHON", database="SCHOOL")
3) mycon.cursor()
4) update STUDENT set MARKS = MARKS + 10 where GRADE = ‘C’
5) mycur.execute(smt)
6) mycon.commit()
7) mycon.close()
21.
Ans: 1) mysql.connector
2) sql.connect(host="localhost", user="ADMIN", password="admin@123",
database="SCHOOL")
3) mycon.cursor()
4) int(input(‘Enter Roll Number : ‘))
5) input(‘Enter Name : ‘)
6) update STUDENT set MARKS = MARKS + 10 where GRADE = ‘C’
7) mycur.execute(smt)
8) mycon.commit()
9) mycon.close()
22.
Ans: 1) mysql.connector
2) sql.connect(host="localhost", user="SCOTT", password="TIGER",
database="ORGANIZATION")
3) conob.cursor()
4) select * form EMPLOYEE where EMPID = ‘EMP30045’
5) mycur.execute(smt)
6) mycur.fetchall()
7) print(rec)
8) conob.close()
23.
Ans: 1) mysql.connector as sql
2) sql.connect(host="localhost", user="PYTHON", password="MYSQL",
database="ORGANIZATION")
3) conobj.cursor()
4) select * form EMPLOYEE where DEPARTMENT = ‘Accounts’
5) mycursor.execute(smt)
6) mycursor.fetchone()
7) rec is not None
8) print(rec)
9) rec = mycursor.fetchone()
10) conobj.close()
Effective Computer Science by Gulshan Sharma 108
24.
Ans: 1) sql.connect(host="localhost", user="ADMINISTRATOR", password="admin@123",
database="ORGANIZATION")
2) conobj.cursor()
3) mycur.execute(smt)
4) mycur.fetchall()
5) continue
6) rec[2]
25.
Ans: 1) sql.connect(host="localhost", user="ADMIN", password="admin@123",
database="COMPANY")
2) conobj.cursor()
3) mycursor.execute(smt)
4) mycursor.fetchone()
5) rec is not None
6) break
7) rec[2]
8) Tuple
9) None
10) Rec = mycursor.fetchone()
11) Total Number of Records : 7
Effective Computer Science by Gulshan Sharma 109
Chapter 3 : Functions
1 b 2 d 3 a 4 a 5 a 6 c 7 b 8 d 9 a 10 d
11 d 12 c 13 a 14 a 15 d 16 c 17 a 18 d 19 a 20 c
21 a 22 d 23 b 24 d 25 c 26 a 27 a 28 d 29 d 30 d
31 d 32 a 33 b 34 d 35 d 36 b 37 a 38 a 39 d 40 b
41 b 42 a 43 d 44 b 45 d 46 d
Chapter 3 : Functions
1 b 2 a 3 a 4 d 5 a 6 a 7 d 8 d 9 b 10 a
11 b 12 a 13 b 14 a 15 b 16 a 17 a 18 a 19 b 20 b
21 a 22 b 23 b 24 b 25 c