List of Programs for Computer Sc.
Practical file - XI
DOWNLOAD
1. Write a program to accepts two integers and print
their sum.
2. Write a program that accepts the radius of a circle
and prints its area.
3. Write a program that accepts base and height and
calculate the area of a triangle.
4. Write a program that inputs a student’s marks in
three subjects (out of 100) and prints the
percentage marks.
5. Write a program to compute the area of square and
triangle.
6. Write a program to calculate simple interest.
7. Write a program to read two numbers and prints
their quotient and reminder.
8. Write a program to find whether a given number is
even or odd.
9. Write a program to find the largest among the
three integers.
10. Write a program to find the lowest among the
three integers.
11. Write a program that accepts the length and
breadth of the rectangle and calculate its area.
12. Write a program that accepts weight in Kg and
height in meters and calculate the BMI.
13. Write a program that reads the number n and
print the value of n², n³ and n⁴.
14. Write a program to accept the marks of five
subjects and calculate the average marks.
15. Write a program to accept the height in cm and
convert it into feet and inches.
16. Write a program that accepts the age and print
if one is eligible to vote or not.
17. Write a program that accepts two numbers and
check if the first number is fully divisible by the
second number or not.
18. Write a program to read base, width and
height of parallelogram and calculate its area and
perimeter.
19. Write a program to accept the year and check
if it is a leap year or not.
20. Write a program to obtain x, y, z and calculate
4x⁴+3y³+9z+6π.
21. Write a program to input a number and print
its square if it is odd, otherwise print its square
root.
22. Write a program to input a number and check
whether it is positive, negative or zero.
23. Write a program to input percentage marks of
a student and find the grade as per the following
criterion:
Marks Grade
>=90 A
75-90 B
60-75 C
Below 60 D
24. Write a program to enter a number and check if it is a
prime number or not.
25. Write a program to display a menu for calculating the area
of the circle or perimeter of the circle.
26. Write a program that reads two numbers and an arithmetic
operator and displays the computed result.
27. Write a program to print whether a given character is an
uppercase or a lowercase character or a digit or any other
character.
28. Write a program to calculate and print the roots of a
quadratic equation ax²+bx+c=0.(a≠0)
29. Write a program to print the sum of natural numbers
between 1 to 7. Print the sum progressively i.e. after adding
each natural number, a print sum so far.
30. Write a program to calculate the factorial of a number.
31. Write a program to create a triangle of stars using a
nested loop.
32. Write a Python script to print Fibonacci series’ first 20
elements.
33. Write a program to read an integer>1000 and reverse the
number.
34. Input three angles and determine if they form a triangle or
not.
35. Write a Python script that displays the first ten Mersenne
numbers.
36. Write a Python script that displays the first ten Mersenne
numbers and displays ‘Prime’ next to Mersenne Prime
Numbers.
37. Write a program to calculate BMI and print the nutritional
status as per the following table:
Nutritional Status WHO criteria BMI
cut-off
Underweight <18.5
Normal 18.5-24.9
Overweight 25-29.9
Obese ≥30
38. Write a python script to print the following pattern.
1 3
1 3 5
1 3 5 7
39. Write a program to find the sum of the series :
s=1+x+x ²+x ³+x ⁴…+x ⁿ
40. Write a python script to input two numbers and print their
LCM and HCF.
41. Write a python script to calculate the sum of the following
series:
S=(1)+(1+2)+(1+2+3)+……+(1+2+3+….+n)
42. Write a program to print the following using a single loop
(no nested loops)
1 1
1 1 1
1 1 1 1
1 1 1 1 1
43. Write a program to print a pattern like:
4321
432
43
44. A program that reads a line and prints its statistics like:
The number of uppercase letters:
The number of lowercase letters:
The number of alphabets:
The number of digits:
45. Write a program that reads a line and a substring and
displays the number of occurrences of the given substring in
the line.
46. Write a program that takes a string with multiple words
and then capitalizes the first letter of each word and forms a
new string out of it.
47. Write a program that reads a string and checks whether it
is a palindrome string or not.
48. Write a program that reads a string and displays the
longest substring of the given string having just the
consonants.
49. Write a program that reads a string and then prints a
string that capitalizes every other letter in the string.
50. Write a program that reads the email id of a person in the
form of a string and ensures that it belongs to domain
@edupillar.com (Assumption: no invalid characters are there in
email-id)
51. WAP to remove all odd numbers from the given list.
52. WAP to display the second largest element of a given list.
53. WAP to display frequencies of all the elements of a list.
54. WAP in Python to find and display the sum of all the values
which are ending with 3 from a list.
55. WAP to search an element from the given list.
56. WAP to accept values from user and create a tuple.
57. Write a program to input the total number of sections and
stream name in 11th class and display all information on the
output screen.
58. Write a program to input the total number of sections and
59. WAP to store students’ details like admission number, roll
number, name and percentage in a dictionary and display
information on the basis of admission number.
60. Write a Python program to remove an item from a tuple.
61. Write a program to input n numbers from the user. Store
these numbers in a tuple. Print the maximum, minimum, sum
and mean of number from this tuple.
Solutions:
1. Write a program to accepts two integers and print their sum.
Download
# Write a program to accepts two integers and print
their sum.
a=int(input('Enter the first integer:'))
b=int(input('Enter the second integer:'))
Sum=a+b
print('The two integers are:', a, b)
print('The sum of two integers are:', Sum)
2. Write a program that accepts the radius of a circle and
prints its area.
Download
# 2.Write a program that accepts radius of a circle
and prints its area.
r=int(input('Enter the radius of circle:'))
Area=3.14*r**2
print('The area of the circle is:', Area)
3. Write a program that accepts base and height and calculate
the area of a triangle.
Download
#Write a program that accepts base and height and
calculate the area of triangle
b=float(input('Enter the base of triangle:'))
h=float(input('Enter the height of triangle:'))
Area=(1/2)*b*h
print('The area of triangle is:', Area)
4.Write a program that inputs a student’s marks in three
subjects (out of 100) and prints the percentage marks.
Download
# Write a program that inputs a student’s marks in
# three subjects (out of 100)and prints the
percentage marks
print('Enter the marks of three subject out of 100')
a=float(input('Enter the marks of first subject:'))
b=float(input('Enter the marks of second subject:'))
c=float(input('Enter the marks of third subject:'))
P=(a+b+c)/3
print('The percentage marks are:', P,'%')
5. Write a program to compute the area of square and triangle.
Download
# Write a program to compute area of square and
triangle.
a=float(input('Enter the value of side:'))
A=a**2
T=((3**0.5)/4)*a**2
print('The area of square is:', A)
print('The area of triangle is:', T)
6. Write a program to calculate simple interest.
Download
# Write a program to calculate simple interest.
P=float(input('Enter the principal amount in : '))
R=float(input('Enter the rate of interest: '))
T=float(input('Enter the time in years: '))
SI=(P*R*T)/100
print('The simple interest is : ', SI)
7. Write a program to read two numbers and prints their
quotient and reminder.
Download
# Write a program to read two numbers and prints
their quotient and reminder
a=float(input('Enter the dividend:'))
b=float(input('Enter the divisor:'))
Q=a//b
R=a%b
print('The quotient is:', Q)
print('The remainder is:', R)
8. Write a program to find whether a given number is even or
odd.
Download
# Write a program to find whether a given number is
even or odd.
a=int(input('Enter the number:'))
if a%2==0:
print('The number is even')
else:
print('The number is odd')
9. Write a program to find the largest among the three
integers.
Download
# Write a program to find largest among three
integers
a=int(input('Enter the first integer:'))
b=int(input('Enter the second integer:'))
c=int(input('Enter the third integer:'))
if a>b and a>c:
print(a, 'is the largest integer')
if b>a and b>c:
print(b, 'is the largest integer')
if c>a and c>b:
print(c, 'is the largest integer')
10. Write a program to find the lowest among the three
integers.
Download
# Write a program to find lowest among three integer.
a=int(input('Enter the first integer:'))
b=int(input('Enter the second integer:'))
c=int(input('Enter the third integer:'))
ifa<b and a<c:
print(a, 'is the smallest integer')
ifb<a and b<c:
print(b, 'is the smallest integer')
ifc<a and c<b:
print(c, 'is the smallest integer')
11. Write a program that accepts the length and
breadth of the rectangle and calculate its area.
Download
# Write a program to that accepts length and
# breadth of rectangle and calculate its area.
l=float(input('Enter the length of rectangle:'))
b=float(input('Enter the breadth of rectangle:'))
area=l*b
print('Rectangle Specifications')
print('Length=',l)
print('Breadth=', b)
print('Area=', area)
Download
12. Write a program that accepts weight in Kg and height in
meters and calculate the BMI.
# Write a program that accepts weight in Kg
# and height in meters and calculate the BMI.
W = float(input('Enter the weight in Kg:'))
H = float(input('Enter height in meters:'))
BMI=W/(H**2)
print('BMI is:', BMI)
13. Write a program that reads the number n and prints the
value of n², n³ and n⁴.
Download
# Write a program that reads the number n
# and print the value of n², n³ and n⁴.
a=float(input('Enter the value of n:'))
b=a**2
c=a**3
d=a**4
print('The value of n² is:', b)
print('The value of n³ is:', c)
print('The value of n⁴ is:', d)
14. Write a program to accept the marks of five subjects and
calculate the average marks.
Download
# Write a program to accept the marks of five
subjects
# and calculate the average marks.
a=float(input('Enter the marks of first subject:'))
b=float(input('Enter the marks of second subject:'))
c=float(input('Enter the marks of third subject:'))
d=float(input('Enter the marks of fourth subject:'))
e=float(input('Enter the marks of fifth subject:'))
Average=(a+b+c+d+e)/5
print('The average marks are:', Average)
15. Write a program to accept the height in cm and convert it
into feet and inches.
Download
# Write a program to accept the height in cm and
# convert it into feet and inches.
a=float(input('Enter your height in centimeters:'))
Feet=a*0.032
Inch=a*0.393
print('Your height in feet is:', Feet)
print('Your height in inch is:', Inch)
16. Write a program that accepts the age and print if one is
eligible to vote or not.
Download
# Write a program that accepts the age and
# print if one is eligible to vote or not.
a=int(input('Enter your age:'))
if a>=18:
print('You are eligible to vote')
else:
print('You are not eligible to vote')
17. Write a program that accepts two numbers and check if
the first number is fully divisible by the second number or not.
Download
# Write a program that accepts two numbers and
# check if the first number is fully divisible by
second number or not.
a=float(input('Enter the first number:'))
b=float(input('Enter the second number:'))
if a%b==0:
print('The first number is fully divisible by
second number')
else:
print('The first number is not fully divisible
by second number')
18. Write a program to read base, width and height of
parallelogram and calculate its area and perimeter.
Download
#Write a program to read base, width and height of
#parallelogram and calculate its area and perimeter.
b=float(input('Enter the base of parallelogram:'))
w=float(input('Enter the width of parallelogram:'))
h=float(input('Enter the height of parallelogram:'))
Area=b*h
Perimeter=2*(b+w)
print('The area of parallelogram is:', Area)
print('The perimeter of parallelogram is:',
Perimeter)
19. Write a program to accept the year and check if it is a leap
year or not.
Download
# Write a program to accept the year and
# check if it is a leap year or not.
a=int(input('Enter the year:'))
if a%4==0:
print('This year is a leap year')
else:
print('This year is not a leap year')
20. Write a program to obtain x, y, z and calculate
4x⁴+3y³+9z+6π.
Download
# Write a program to obtain x, y, z and calculate
4x⁴+3y³+9z+6π.
import math
print('To calculate 4x⁴+3y³+9z+6π')
x=float(input('Enter the number x:'))
y=float(input('Enter the number y:'))
z=float(input('Enter the number z:'))
b=(4*math.pow(x,4))+(3*math.pow(y,3))+(9*z)
+(6*math.pi)
print('The result of the above expression is:',b)
21. Write a program to input a number and print its square if it
is odd, otherwise print its square root.
Download
# Write a program to input a number and print its
# square if it is odd, otherwise print its square
root.
import math
x=float(input('Enter the number:'))
a=math.pow(x,2)
b=math.sqrt(x)
if x%2!=0:
print('The value of square is:',a)
else:
print('The value of square root is:',b)
Download
22. Write a program to input a number and check whether it is
positive, negative or zero.
# Write a program to input a number and check whether
# it is positive, negative or zero.
a=float(input('Enter the number:'))
if a>=0:
if a==0:
print('The number is zero')
else:
print('The number is a positive number')
else:
print('The number is a negative number')
23. Write a program to input percentage marks of a student
and find the grade as per the following criterion:
Download
'''
Write a program to input percentage marks of a
student and find the grade as per following
criterion:
Marks Grade
>=90 A
75-90 B
60-75 C
Below 60 D
'''
a=float(input('Enter the percentage marks:'))
if a>=90:
print('The student has got an A grade')
elif a>=75 and a<90:
print('The student has got a B grade')
elif a>=60 and a<75:
print('The student has got a C grade')
else:
print('The student has got a D grade')
24. Write a program to enter a number and check if it is a
prime number or not.
Download
# Write a program to enter a number and
# check if it is a prime number or not.
num=int(input('Enter the number:'))
for i in range(2,num//2+1):
if num%i==0:
print('It is not a prime no.')
break
else:
print('It is a prime number')
25. Write a program to display a menu for calculating the area
of the circle or perimeter of the circle.
Download
# Write a program to display a menu for calculating
# area of circle or perimeter of the circle.
r=float(input('Enter the radius of the circle:'))
print('1.Calculate perimeter')
print('2.Calculate area')
choice=int(input('Enter your choice (1 or 2):'))
if choice==1:
peri=2*3.14159*r
print('Perimeter of the circle with
radius',r,':',peri)
else:
area=3.14159*r*r
print('Area of the circle of the
radius',r,':',area)
26. Write a program that reads two numbers and an arithmetic
operator and displays the computed result.
Download
# Write a program that reads two numbers and an
# arithmetic operator and displays the computed
result.
a=float(input('Enter the first number:'))
b=float(input('Enter the second number:'))
c=input('Enter the operator[/,*,+,-]:')
if c=='/':
r=a/b
elif c=='*':
r=a*b
elif c=='+':
r=a+b
elif c=='-':
r=a-b
else:
print('Invalid operator')
print(a,c,b,'=',r)
27. Write a program to print whether a given character is an
uppercase or a lowercase character or a digit or any other
character.
Download
# Write a program to print whether a given character
# is an uppercase or a lowercase character or a digit
or any other character.
ch=input('Enter a single character:')
if ch>='A'and ch<='Z':
print('You have entered an uppercase
character.')
elif ch>='a'and ch<='z':
print('You have entered an lowercase
character.')
elif ch>='0'and ch<='9':
print('You have entered a digit.')
else:
print('You have entered a special character.')
28. Write a program to calculate and print the roots of a
quadratic equation ax²+bx+c=0.(a≠0)
Download
# Write a program to calculate and print the roots of
a
# quadratic equation ax²+bx+c=0.(a≠0)
import math
print('For quadratic equation, ax²+bx+c=0,enter
coefficents below')
a=int(input('Enter a:'))
b=int(input('Enter b:'))
c=int(input('Enter c:'))
if a==0:
print('Value of a should not be zero')
print('Aborting!!')
else:
d=b*b-4*a*c
if d>0:
root1=(-b+math.sqrt(d))/(2*a)
root2=(-b-math.sqrt(d))/(2*a)
print('Roots are real and unequal')
print('Root1=',root1,',Root2=',root2)
elif d==0:
root1=-b/2*a
print('Roots are real and equal')
print('Root1=',root1,',Root2=',root1)
else:
print('Roots are complex and imaginary')
29. Write a program to print the sum of natural numbers
between 1 to 7. Print the sum progressively i.e. after adding
each natural number, a print sum so far.
Download
# Write a program to print the sum of natural numbers
between 1 to 20.
# Print the sum progressively i.e. after adding each
natural number,
# print sum so far.
Sum=0
for n in range(1,21):
Sum+=n
print('Sum of natural numbers <=',n,'is',Sum)
30. Write a program to calculate the factorial of a number.
Download
# Write a program to calculate the factorial of a
number.
num=int(input('Enter a number:'))
fact=1
a=1
while a<=num:
fact*=a
a+=1
print('The factorial of',num,'is',fact)
31. Write a program to create a triangle of stars using a
nested loop.
Download
# Write a program to create a triangle of stars using
nested loop.
for i in range(1,6):
print()
for j in range(1,i):
print('*',end=' ')
32. Write a Python script to print Fibonacci series’ first 20
elements.
Download
# Write a Python script to print Fibonacci series’
first 10 elements.
first=0
second=1
print(first, end=' ')
print(second,end=' ')
for a in range(1,9):
third=first+second
print(third,end=' ')
first,second=second,third
33. Write a program to read an integer>1000 and reverse the
number.
Download
# Write a program to read an integer>1000 and reverse
the number.
num=int(input('Enter a number (>1000):'))
tnum=num
reverse=0
while tnum>0:
digit=tnum%10
reverse=reverse*10+digit
tnum=tnum//10
print('Reverse of',num,'is',reverse)
34. Input three angles and determine if they form a triangle or
not.
Download
# Input three angles and determine if they form a
triangle or not.
angle1=angle2=angle3=0
angle1=float(input('Enter the first angle:'))
angle2=float(input('Enter the second angle:'))
angle3=float(input('Enter the third angle:'))
if angle1+angle2+angle3==180:
print('The angles form a triangle')
else:
print('The angles do not form a triangle')
35. Write a Python script that displays the first ten Mersenne
numbers.
Download
# Write a Python script that displays first ten
Mersenne numbers.
print('First 10 Mersenne numbers are:')
for a in range(1,11):
mersnum=2**a-1
print(mersnum,end=' ')
print()
36. Write a Python script that displays the first ten Mersenne
numbers and displays ‘Prime’ next to Mersenne Prime
Numbers.
Download
# Write a Python script that displays first ten
# Mersenne numbers and displays ‘Prime’ next to
Mersenne Prime Numbers.
for a in range(1,21):
mersnum=2**a-1
mid=mersnum//2+1
for b in range(2,mid):
if mersnum%b==0:
print(mersnum)
break
else:
print(mersnum,'\tPrime')
37. Write a program to calculate BMI and print the nutritional
status as per the following table:
Download
'''
# Write a program to calculate BMI and print
# the nutritional status as per following table:
Nutritional WHO criteria
Status (BMI cut-off)
Underweight <18.5
Normal 18.5-24.9
Overweight 25-29.9
Obese ≥30
'''
w=float(input('Enter the weight in kgs:'))
h=float(input('Enter the height in meters:'))
BMI=w/h**2
print('BMI is',BMI,end='')
if BMI<18.5:
print('...Underweight')
elif BMI>=18.5 and BMI<24.9:
print('...Normal')
elif BMI>=25 and BMI<29.9:
print('...Overweight')
else:
print('...Obese')
38. Write a python script to print the following pattern.
1 3
1 3 5
1 3 5 7
Download
# Write python script to print the following pattern.
'''
1
1 3
1 3 5
1 3 5 7
'''
for a in range(3,10,2):
print()
for b in range(1,a,2):
print(b, end=' ')
print()
39. Write a program to find the sum of the series :
s=1+x+x ²+x ³+x ⁴…+x ⁿ
Download
# Write a program to find sum of series :
s=1+x+x²+x³+x⁴…+xⁿ
x=float(input('Enter the value of x:'))
n=int(input('Enter the value of n (for x**n):'))
s=0
for a in range(n+1):
s+=x**a
print('Sum of first' ,n,'terms:',s)
Download
40. Write a python script to input two numbers and print their
LCM and HCF.
#40.Write a python script to input two numbers
#and print their lcm and hcf.
x=int(input('Enter the first number:'))
y=int(input('Enter the second number:'))
if x>y:
smaller=y
else:
smaller=x
for i in range(1,smaller+1):
if x%i==0 and y%i==0:
hcf=i
lcm=(x*y)/hcf
print('The HCF of',x,'and',y,'is:',hcf)
print('The LCM of',x,'and',y,'is:',lcm)
41. Write a python script to calculate the sum of the following
series:
S=(1)+(1+2)+(1+2+3)+……+(1+2+3+….+n)
Download
# Write a python script to calculate the
# sum of the following series: S=(1)+(1+2)+(1+2+3)+……
+(1+2+3+….+n)
Sum=0
n=int(input('How many terms?'))
for a in range(2,n+2):
term=0
for b in range(1,a):
term+=b
print('Term',(a-1),':',term)
Sum+=term
print('Sum of',n,'terms is:',Sum)
42. Write a program to print the following using a single loop
(no nested loops)
1 1
1 1 1
1 1 1 1
1 1 1 1 1
Download
'''
42.Write a program to print the following using a
single loop (no nested loops)
1
11
111
1111
11111
'''
n=1
for a in range(5):
print(n,end = ' ')
print()
n=n*10+1
Download
43. Write a program to print a pattern like:
4321
432
43
'''
Write a program to print a pattern like:
4 3 2 1
4 3 2
4 3
4
'''
for i in range(4):
for j in range(4,i,-1):
print(j,end=' ')
else:
print()
44. A program that reads a line and prints its statistics like:
The number of uppercase letters:
The number of lowercase letters:
The number of alphabets:
The number of digits:
Download
#Program that reads a line and print its statistics
like:
'''
Number of uppercase letters:
Number of lowercase letters:
Number of alphabets:
Number of digits:
'''
line=input('Enter a line:')
lowercount=uppercount=0
digitcount=alphacount=0
for a in line:
if a.islower():
lowercount+=1
elif a.isupper():
uppercount+=1
elif a.isdigit():
digitcount+=1
if a.isalpha():
alphacount+=1
print('Number of uppercase letters are:',uppercount)
print('Number of lowercase letters are:',lowercount)
print('Number of alphabets are:',alphacount)
print('Number of digits are:',digitcount)
45. Write a program that reads a line and a substring and
displays the number of occurrences of the given substring in
the line.
Download
#Write a program that reads a line and a substring
#and displays the number of occurrences of the given
substring in the line.
line=input('Enter line:')
sub=input('Enter substring:')
length=len(line)
lensub=len(sub)
start=count=0
end=length
while True:
pos=line.find(sub,start,end)
if pos!=-1:
count+=1
start=pos+lensub
else:
break
if start>=length:
break
print('No. of occurences of',sub,':',count)
46. Write a program that takes a string with multiple words
and then capitalizes the first letter of each word and forms a
new string out of it.
Download
#Write a program that takes a string with multiple
#words and then capitalizes the first letter of each
word
#and forms a new string out of it.
string=input('Enter a string:')
length=len(string)
a=0
end=length
string2=''
while a<length:
if a==0:
string2+=string[0].upper()
a+=1
elif(string[a]==' ' and string[a+1]!=' '):
string2+=string[a]
string2+=string[a+1].upper()
a+=2
elif (string[a]==',' and string[a+1]!=','):
string2+=string[a]
string2+=string[a+1].upper()
a+=2
else:
string2+=string[a]
a+=1
print('Original string:',string)
print('Capitalized words string:',string2)
47. Write a program that reads a string and checks whether it
is a palindrome string or not.
Download
#Write a program that reads a string and
#checks whether it is a palindrome string or not.
string=input('Enter a string:')
length=len(string)
mid=length//2
rev=-1
for a in range(mid):
if string[a]==string[rev]:
print(string,'is a palindrome.')
break
else:
print(stri
Download
48. Write a program that reads a string and displays the
longest substring of the given string having just the
consonants.
#Write a program that reads a string and displays
#the longest substring of the given string having
#just the consonants.
string=input('Enter a string:')
length=len(string)
maxlength=0
maxsub=''
sub=''
lensub=0
for a in range(length):
if string[a] in 'aeiou' or string[a] in 'AEIOU':
if lensub>maxlength:
maxsub=sub
maxlength=lensub
sub=''
lensub=0
else:
sub+=string[a]
lensub=len(sub)
a+=1
print('Maximum length consonant substring
is:',maxsub,end=' ')
print('with',maxlength,'characters')
49. Write a program that reads a string and then prints a
string that capitalizes every other letter in the string.
Download
# Write a program that reads a string and then
# prints a string that capitalizes every other letter
in the string.
string=input('Enter a string:')
length=len(string)
print('Original string:',string)
string2=''
for a in range(0,length,2):
string2+=string[a]
if a<length-1:
string2+=string[a+1].upper()
print('Alternatively capitalized string:',string2)
Download
50. Write a program that reads the email id of a person in the
form of a string and ensures that it belongs to domain
@edupillar.com (Assumption: no invalid characters are there in
email-id)
# Write a program that reads the email id of a person
# in the form of a string and ensures that it belongs
to
# domain @learnpython4cbse.com(Assumption:no invalid
characters
# are there in email-id)
email=input('Enter your email id:')
domain='@learnpython4cbse.com'
ledo=len(domain) #ledo=length of domain
lema=len(email) #lema=length of email
sub=email[lema-ledo:]
if sub==domain:
if ledo!=lema:
print('It is valid email id')
else:
print('This is invalid email id- contains
just the domain name')
else:
print('This email-d is either not valid or
belongs to some other domain')
51. WAP to remove all odd numbers from the given list.
Download
# WAP to remove all odd numbers from the given list.
L= [2, 7,12, 5,10,15,23]
for i in L:
if i%2!=0:
L.remove (i)
print (L)
Download
52. WAP to display the second largest element of a given list.
# WAP to display second largest element of a given
list.
L= [ 41, 6, 9, 13,4, 23]
m=max (L)
secmax=L[0]
for i in range(1, len(L) ) :
if L[i]>secmax and L[i]<m:
secmax=L[i]
print ('The second largest element is: ',secmax)
53. WAP to display frequencies of all the elements of a list.
Download
# WAP to display frequencies of all the elements of a
list.
L= [3, 21, 5, 6, 3, 8, 21, 6]
L1= [ ]
L2= [ ]
print ('Element' , ' \t' , 'frequency' )
for i in L:
if i not in L2:
x=L.count(i)
L1.append(x)
L2.append(i)
for i in range(len(L1)):
print (L2[i],'\t\t\t',L1[i])
54. WAP in Python to find and display the sum of all the values
which are ending with 3 from a list.
Download
# WAP in Python to find and display the sum of all
the values which are ending with 3 from a list.
L=[33,13,92,99,3,12]
sum=0
x=len (L)
for i in range(0,x):
if type (L [i])== int:
if L[i]%10==3:
sum+=L[i]
print (s
55. WAP to search an element from the given list.
Download
# WAP to search an element from the list
L=eval(input("Enter the elements:"))
n=len(L)
flag =1
s = int(input("Enter the element to be searched:"))
for i in range(0,n-1):
if(L[i]==s):
flag=1
break;
else:
flag=0
if flag==1:
print("Element found")
else:
print("Elemnet not found")
Download
56. WAP to accept values from user and create a tuple.
# WAP to accept values from user and create a tuple.
t=tuple()
n=int(input("How many values you want to enter: "))
for i in range(n):
a=input("Enter Number: ")
t=t+(a,)
print("Entered Numbers are: ")
print(t)
57. Write a program to input the total number of sections and
stream name in 11th class and display all information on the
output screen.
Download
# WAP to input any two tuples and swap their values
t1 = tuple()
n = int (input("Total no of values in First tuple:
"))
for i in range(n):
a = input("Enter Elements : ")
t1 = t1 + (a,)
t2 = tuple()
m = int (input("Total no of values in Second tuple:
"))
for i in range(m):
a = input("Enter Elements : ")
t2 = t2 + (a,)
print("First Tuple : ")
print(t1)
print("Second Tuple : ")
print(t2)
t1,t2 = t2, t1
print("After Swapping: ")
print("First Tuple : ")
print(t1)
print("Second Tuple : ")
print(t2)
58. Write a program to input the total number of sections and
Download
# Write a program to input total number of sections
and
#stream name in 11th class and display all
information
#on the output screen.
classxi=dict()
n=int(input("Enter total number of section in xi
class: "))
i=1
while i<=n:
a=input("Enter Section: ")
b=input ("Enter stream name: ")
classxi[i]=b
i=i+1
print ("Class",'\t''Section''\t''Stream name')
for i in classxi:
print ("XI",'\t',i,'\t',classxi[i])
59. WAP to store students’ details like admission number, roll
number, name and percentage in a dictionary and display
information on the basis of admission number.
Download
# WAP to store students’ details like admission
number, roll number,
# name and percentage in a dictionary and display
information on the
# basis of admission number.
record = dict ()
i=1
n= int (input ("How many records u want to enter: "))
while(i<=n):
Adm = input("Enter Admission number: ")
roll = input("Enter Roll Number: ")
name = input("Enter Name :")
perc = float(input("Enter Percentage : "))
t = (roll,name, perc)
record[Adm] = t
i = i + 1
Nkey = record.keys()
for i in Nkey:
print("\nAdmno- ", i, " :")
r = record[i]
print("Roll No\t", "Name\t", "Percentage\t")
for j in r:
print(j, end = "\t")
60. Write a Python program to remove an item from a tuple.
Download
# Write a Python program to remove an item from a
tuple.
#create a tuple
tuplex =
"l","e","a","r","n","p","y","t","h","o","n","4","c","
b","s","e"
print("Tuple Before Removing an item")
print(tuplex)
#converting the tuple to list
listx = list(tuplex)
#use different ways to remove an item of the list
listx.remove("4")
#converting the tuple to list
tuplex = tuple(listx)
print("\nTuple After Removing an item '4'")
print(tuplex)
61. Write a program to input n numbers from the user. Store
these numbers in a tuple. Print the maximum, minimum, sum
and mean of number from this tuple.
Download
# Write a program to input n numbers from the user.
# Store these numbers in a tuple. Print the maximum,
# minimum, sum and mean of number from this tuple.
numbers = tuple() #create an empty tuple 'numbers'
n = int(input("How many numbers you want to enter?:
"))
print("Enter any ",n," numbers")
for i in range(0,n):
num = int(input())
#it will assign numbers entered by user to tuple
'numbers'
numbers = numbers +(num,)
print('\nThe numbers in the tuple are:')
print(numbers)
print("\nThe maximum number is: ")
print(max(numbers))
print("The minimum number is: ")
print(min(numbers))
print("The sum of numbers is: ")
print(sum(numbers))
print("The mean of numbers is: ")
mean = sum(numbers)/(i+1)
print(mean)
ele=int(input("Enter the element to be searched: "))
if ele in numbers:
print("Element found")
else:
print("Element not found")
List of Programs for Computer Sc.
Practical file - XII
1. Write a Program to show whether entered numbers are
prime or not in the given range.
2. Input a string and determine whether it is a palindrome or
not.
3. Find the largest/smallest number in a list/tuple
4. WAP to input any two tuples and swap their values.
5. WAP to store students’ details like admission number, roll
number, name and percentage in a dictionary and display
information on the basis of admission number.
6. Write a program with a user-defined function with string
as a parameter which replaces all vowels in the string
with ‘*’.
7. Recursively find the factorial of a natural number.
8. Write a recursive code to find the sum of all elements of a
list.
9. Write a recursive code to compute the nth Fibonacci
number.
10. Read a text file line by line and display each word
separated by a #.
11. Read a text file and display the number of vowels/
consonants/ uppercase/ lowercase and other than
character and digit in the file.
12. Write a Python code to find the size of the file in
bytes, the number of lines, number of words and no. of
character.
13. Write a program that accepts a filename of a text
file and reports the file's longest line.
14. Create a binary file with the name and roll number.
Search for a given roll number and display the name, if
not found display appropriate message.
15. Create a binary file with roll number, name and
marks. Input a roll number and update details.
16. Remove all the lines that contain the character `a' in
a file and write it to another file.
17. Write a program to perform read and write operation
onto a student.csv file having fields as roll number, name,
stream and percentage.
18. Program to search the record of a particular student
from CSV file on the basis of inputted name.
19. Write a random number generator that generates
random numbers between 1 and 6 (simulates a dice).
20. Write a program to create a library in python and
import it in a program.
21. Write a python program to implement sorting
techniques based on user choice using a list data-
structure. (bubble/insertion)
22. Take a sample of ten phishing e-mails (or any text
file) and find the most commonly occurring word(s).
23. Write a python program to implement a stack using
a list data-structure.
24. Write a program to implement a queue using a list
data structure.
25. Write a python program to implement searching
methods based on user choice using a list data-structure.
(linear & binary)
DOWNLOAD
1. Write a Program to show whether entered numbers are
prime or not in the given range.
Download
lower=int(input("Enter lowest number as lower bound
to check : "))
upper=int(input("Enter highest number as upper bound
to check: "))
c=0
for i in range(lower, upper+1):
if (i == 1):
continue
# flag variable to tell if i is prime or not
flag = 1
for j in range(2, i // 2 + 1):
if (i % j == 0):
flag = 0
break
# flag = 1 means i is prime
# and flag = 0 means i is not prime
if (flag == 1):
print(i, end = " ")
2. Input a string and determine whether it is a palindrome or
not.
Download
string=input('Enter a string:')
length=len(string)
mid=length//2
rev=-1
for a in range(mid):
if string[a]==string[rev]:
print(string,'is a palindrome.')
break
else:
print(string,'is not a palindrome.')
3. Find the largest/smallest number in a list/tuple
Download
# creating empty list
list1 = []
# asking number of elements to put in list
num = int(input("Enter number of elements in list:
"))
# iterating till num to append elements in list
for i in range(1, num + 1):
ele= int(input("Enter elements: "))
list1.append(ele)
# print maximum element
print("Largest element is:", max(list1))
# print minimum element
print("Smallest element is:", min(list1))
4. WAP to input any two tuples and swap their values.
Download
t1 = tuple()
n = int (input("Total no of values in First tuple:
"))
for i in range(n):
a = input("Enter Elements : ")
t1 = t1 + (a,)
t2 = tuple()
m = int (input("Total no of values in Second tuple:
"))
for i in range(m):
a = input("Enter Elements : ")
t2 = t2 + (a,)
print("First Tuple : ")
print(t1)
print("Second Tuple : ")
print(t2)
t1,t2 = t2, t1
print("After Swapping: ")
print("First Tuple : ")
print(t1)
print("Second Tuple : ")
print(t2)
5. WAP to store students’ details like admission number, roll
number, name and percentage in a dictionary and display
information on the basis of admission number.
Download
record = dict ()
i=1
n= int (input ("How many records u want to enter: "))
while(i<=n):
Adm = input("Enter Admission number: ")
roll = input("Enter Roll Number: ")
name = input("Enter Name :")
perc = float(input("Enter Percentage : "))
t = (roll,name, perc)
record[Adm] = t
i = i + 1
Nkey = record.keys()
for i in Nkey:
print("\nAdmno- ", i, " :")
r = record[i]
print("Roll No\t", "Name\t", "Percentage\t")
for j in r:
print(j, end = "\t")
6. Write a program with a user-defined function with string as a
parameter which replaces all vowels in the string with ‘*’.
Download
def strep(str):
# convert string into list
str_lst =list(str)
# Iterate list
for i in range(len(str_lst)):
# Each Character Check with Vowels
if str_lst[i] in 'aeiouAEIOU':
# Replace ith position vowel with'*'
str_lst[i]='*'
#to join the characters into a new string.
new_str = "".join(str_lst)
return new_str
def main():
line = input("Enter string: ")
print("Orginal String")
print(line)
print("After replacing Vowels with '*'")
print(strep(line))
main()
7. Recursively find the factorial of a natural number.
Download
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
def main():
n = int(input("Enter any number: "))
print("The factorial of given number is:
",factorial(n))
main()
8. Write a recursive code to find the sum of all elements of a
list.
Download
def lstSum(lst,n):
if n==0:
return 0
else:
return lst[n-1]+lstSum(lst,n-1)
mylst = [] # Empty List
#Loop to input in list
num = int(input("Enter how many number :"))
for i in range(num):
n = int(input("Enter Element "+str(i+1)+":"))
mylst.append(n) #Adding number to list
sum = lstSum(myl
st,len(mylst))
print("Sum of List items ",mylst, " is :",sum)
9. Write a recursive code to compute the nth Fibonacci
number.
Download
def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return(fibonacci(n-2) + fibonacci(n-1))
nterms = int(input("Please enter the Range Number:
"))
# check if the number of terms is valid
if nterms <= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(fibonacci(i),end=' ')
10.Read a text file line by line and display each word
separated by a #.
Download
filein = open("Mydoc.txt",'r')
line =" "
while line:
line = filein.readline()
#print(line)
for w in line:
if w == ' ':
print('#',end = '')
else:
print(w,end = '')
filein.close()
'''
#-------------OR------------------
filein = open("Mydoc.txt",'r')
for line in filein:
word= line .split()
for w in word:
print(w + '#',end ='')
print()
filein.close()
'''
11. Read a text file and display the number of vowels/
consonants/ uppercase/ lowercase characters and other than
character and digit in the file.
Download
filein = open("Mydoc1.txt",'r')
line = filein.read()
count_vow = 0
count_con = 0
count_low = 0
count_up = 0
count_digit = 0
count_other = 0
print(line)
for ch in line:
if ch.isupper():
count_up +=1
if ch.islower():
count_low += 1
if ch in 'aeiouAEIOU':
count_vow += 1
if ch.isalpha():
count_con += 1
if ch.isdigit():
count_digit += 1
if not ch.isalnum() and ch !=' ' and ch !='\n':
count_other += 1
print("Digits",count_digit)
print("Vowels: ",count_vow)
print("Consonants: ",count_con-count_vow)
print("Upper Case: ",count_up)
print("Lower Case: ",count_low)
print("other than letters and digit: ",count_other)
filein.close()
12. Write a Python code to find the size of the file in bytes, the
number of lines, number of words and no. of character.
Download
import os
lines = 0
words = 0
letters = 0
filesize = 0
for line in open("Mydoc.txt"):
lines += 1
letters += len(line)
# get the size of file
filesize = os.path.getsize("Mydoc.txt")
# A flag that signals the location outside the
word.
pos = 'out'
for letter in line:
if letter != ' ' and pos == 'out':
words += 1
pos = 'in'
elif letter == ' ':
pos = 'out'
print("Size of File is",filesize,'bytes')
print("Lines:", lines)
print("Words:", words)
print("Letters:", letters)
13. Write a program that accepts a filename of a text file and
reports the file's longest line.
Download
def get_longest_line(filename):
large_line = ''
large_line_len = 0
with open(filename, 'r') as f:
for line in f:
if len(line) > large_line_len:
large_line_len = len(line)
large_line = line
return large_line
filename = input('Enter text file Name: ')
print (get_longest_line(filename+".txt"))
14. Create a binary file with the name and roll number. Search
for a given roll number and display the name, if not found
display appropriate message.
Download
import pickle
def Writerecord(sroll,sname):
with open ('StudentRecord1.dat','ab') as Myfile:
srecord={"SROLL":sroll,"SNAME":sname}
pickle.dump(srecord,Myfile)
def Readrecord():
with open ('StudentRecord1.dat','rb') as Myfile:
print("\n-------DISPALY STUDENTS
DETAILS--------")
print("\nRoll No.",' ','Name','\t',end='')
print()
while True:
try:
rec=pickle.load(Myfile)
print(' ',rec['SROLL'],'\t
' ,rec['SNAME'])
except EOFError:
break
def Input():
n=int(input("How many records you want to
create :"))
for ctr in range(n):
sroll=int(input("Enter Roll No: "))
sname=input("Enter Name: ")
Writerecord(sroll,sname)
def SearchRecord(roll):
with open ('StudentRecord1.dat','rb') as Myfile:
while True:
try:
rec=pickle.load(Myfile)
if rec['SROLL']==roll:
print("Roll NO:",rec['SROLL'])
print("Name:",rec['SNAME'])
except EOFError:
print("Record not find..............")
print("Try Again..............")
break
def main():
while True:
print('\nYour Choices are: ')
print('1.Insert Records')
print('2.Dispaly Records')
print('3.Search Records (By Roll No)')
print('0.Exit (Enter 0 to exit)')
ch=int(input('Enter Your Choice: '))
if ch==1:
Input()
elif ch==2:
Readrecord()
elif ch==3:
r=int(input("Enter a Rollno to be Search:
"))
SearchRecord(r)
else:
break
main()
15. Create a binary file with roll number, name and marks.
Input a roll number and update details.
Download
def Writerecord(sroll,sname,sperc,sremark):
with open ('StudentRecord.dat','ab') as Myfile:
srecord={"SROLL":sroll,"SNAME":sname,"SPERC":sperc,
"SREMARKS":sremark}
pickle.dump(srecord,Myfile)
def Readrecord():
with open ('StudentRecord.dat','rb') as Myfile:
print("\n-------DISPALY STUDENTS
DETAILS--------")
print("\nRoll No.",' ','Name','\t',end='')
print('Percetage',' ','Remarks')
while True:
try:
rec=pickle.load(Myfile)
print(' ',rec['SROLL'],'\t
' ,rec['SNAME'],'\t ',end='')
print(rec['SPERC'],'\t
',rec['SREMARKS'])
except EOFError:
break
def Input():
n=int(input("How many records you want to
create :"))
for ctr in range(n):
sroll=int(input("Enter Roll No: "))
sname=input("Enter Name: ")
sperc=float(input("Enter Percentage: "))
sremark=input("Enter Remark: ")
Writerecord(sroll,sname,sperc,sremark)
def Modify(roll):
with open ('StudentRecord.dat','rb') as Myfile:
newRecord=[]
while True:
try:
rec=pickle.load(Myfile)
newRecord.append(rec)
except EOFError:
break
found=1
for i in range(len(newRecord)):
if newRecord[i]['SROLL']==roll:
name=input("Enter Name: ")
perc=float(input("Enter Percentage: "))
remark=input("Enter Remark: ")
newRecord[i]['SNAME']=name
newRecord[i]['SPERC']=perc
newRecord[i]['SREMARKS']=remark
found =1
else:
found=0
if found==0:
print("Record not found")
with open ('StudentRecord.dat','wb') as Myfile:
for j in newRecord:
pickle.dump(j,Myfile)
def main():
while True:
print('\nYour Choices are: ')
print('1.Insert Records')
print('2.Dispaly Records')
print('3.Update Records')
print('0.Exit (Enter 0 to exit)')
ch=int(input('Enter Your Choice: '))
if ch==1:
Input()
elif ch==2:
Readrecord()
elif ch==3:
r =int(input("Enter a Rollno to be
update: "))
Modify(r)
else:
break
main()
16. Remove all the lines that contain the character `a' in a file
and write it to another file
Download
f1 = open("Mydoc.txt")
f2 = open("copyMydoc.txt","w")
for line in f1:
if 'a' not in line:
f2.write(line)
print('## File Copied Successfully! ##')
f1.close()
f2.close()
f2 = open("copyMydoc.txt","r")
print(f2.read())
17. Write a program to perform read and write operation onto
a student.csv file having fields as roll number, name, stream
and percentage.
Download
import csv
with open('Student_Details.csv','w',newline='') as
csvf:
writecsv=csv.writer(csvf,delimiter=',')
choice='y'
while choice.lower()=='y':
rl=int(input("Enter Roll No.: "))
n=input("Enter Name: ")
p=float(input("Enter Percentage: "))
r=input("Enter Remarks: ")
writecsv.writerow([rl,n,p,r])
print(" Data saved in Student Details
file..")
choice=input("Want add more
record(y/n).....")
with open('Student_Details.csv','r',newline='') as
fileobject:
readcsv=csv.reader(fileobject)
for i in readcsv:
print(i)
18. Program to search the record of a particular student from
CSV file on the basis of inputted name.
Download
import csv
#input Roll number you want to search
number = input('Enter number to find: ')
found=0
#read csv, and split on "," the line
with open('Student_Details.csv') as f:
csv_file = csv.reader(f, delimiter=",")
#loop through csv list
for row in csv_file:
#if current rows index value (here 0) is equal
to input, print that row
if number ==row[0]:
print (row)
found=1
else:
found=0
if found==1:
pass
else:
print("Record Not found")
19. Write a random number generator that generates random
numbers between 1 and 6 (simulates a dice).
Download
import random
import random
def roll_dice():
print (random.randint(1, 6))
print("""Welcome to my python random dice program!
To start press enter! Whenever you are over, type
quit.""")
flag = True
while flag:
user_prompt = input(">")
if user_prompt.lower() == "quit":
flag = False
else:
print("Rolling dice...\nYour number is:")
roll_dice()
20. Write a program to create a library in python and import it
in a program.
Download
#Let's create a package named Mypackage, using the
following steps:
#• Create a new folder named NewApp in D drive (D:\
NewApp)
#• Inside NewApp, create a subfolder with the name
'Mypackage'.
#• Create an empty __init__.py file in the Mypackage
folder
#• Create modules Area.py and Calculator.py in
Mypackage folder with following code
# Area.py Module
import math
def rectangle(s1,s2):
area = s1*s2
return area
def circle(r):
area= math.pi*r*r
return area
def square(s1):
area = s1*s1
return area
def triangle(s1,s2):
area=0.5*s1*s2
return area
# Calculator.py Module
def sum(n1,n2):
s = n1 + n2
return s
def sub(n1,n2):
r = n1 - n2
return r
def mult(n1,n2):
m = n1*n1
return m
def div(n1,n2):
d=n1/n2
return d
# main() function
from Mypackage import Area
from Mypackage import Calculator
def main():
r = float(input("Enter Radius: "))
area =Area.circle(r)
print("The Area of Circle is:",area)
s1 = float(input("Enter side1 of rectangle: "))
s2 = float(input("Enter side2 of rectangle: "))
area = Area.rectangle(s1,s2)
print("The Area of Rectangle is:",area)
s1 = float(input("Enter side1 of triangle: "))
s2 = float(input("Enter side2 of triangle: "))
area = Area.triangle(s1,s2)
print("The Area of TriRectangle is:",area)
s = float(input("Enter side of square: "))
area =Area.square(s)
print("The Area of square is:",area)
num1 = float(input("\nEnter First number :"))
num2 = float(input("\nEnter second number :"))
print("\nThe Sum is :
",Calculator.sum(num1,num2))
print("\nThe Multiplication is :
",Calculator.mult(num1,num2))
print("\nThe sub is :
",Calculator.sub(num1,num2))
print("\nThe Division is :
",Calculator.div(num1,num2))
main()
21. Write a python program to implement sorting techniques
based on user choice using a list data-structure.
(bubble/insertion)
Download
#BUBBLE SORT FUNCTION
def Bubble_Sort(nlist):
for passnum in range(len(nlist)-1,0,-1):
for i in range(passnum):
if nlist[i]>nlist[i+1]:
temp = nlist[i]
nlist[i] = nlist[i+1]
nlist[i+1] = temp
#INSERTION SORT FUNCTION
def Insertion_Sort(nlist):
for index in range(1,len(nlist)):
currentvalue = nlist[index]
position = index
while position>0 and nlist[position-
1]>currentvalue:
nlist[position]=nlist[position-1]
position = position-1
nlist[position]=currentvalue
# DRIVER CODE
def main():
print ("SORT MENU")
print ("1. BUBBLE SORT")
print ("2. INSERTION SORT")
print ("3. EXIT")
choice=int(input("Enter your Choice [ 1 - 3 ]:
"))
nlist = [14,46,43,27,57,41,45,21,70]
if choice==1:
print("Before Sorting: ",nlist)
Bubble_Sort(nlist)
print("After Bubble Sort: ",nlist)
elif choice==2:
print("Before Sorting: ",nlist)
Insertion_Sort(nlist)
print("After Insertion Sort: ",nlist)
else:
print("Quitting.....!")
main()
22. Take a sample of ten phishing e-mails (or any text file) and
find the most commonly occurring word(s).
Download
def Read_Email_File():
import collections
fin = open('email.txt','r')
a= fin.read()
d={ }
L=a.lower().split()
for word in L:
word = word.replace(".","")
word = word.replace(",","")
word = word.replace(":","")
word = word.replace("\"","")
word = word.replace("!","")
word = word.replace("&","")
word = word.replace("*","")
for k in L:
key=k
if key not in d:
count=L.count(key)
d[key]=count
n = int(input("How many most common words to
print: "))
print("\nOK. The {} most common words are as
follows\n".format(n))
word_counter = collections.Counter(d)
for word, count in word_counter.most_common(n):
print(word, ": ", count)
fin.close()
#Driver Code
def main():
Read_Email_File()
main()
23. Write a python program to implement a stack using a list
data-structure.
Download
def isempty(stk):
if stk==[]:
return True
else:
return False
def push(stk,item):
stk.append(item)
top=len(stk)-1
def pop(stk):
if isempty(stk):
return "underflow"
else:
item=stk.pop()
if len(stk)==0:
top=None
else:
top=len(stk)-1
return item
def peek(stk):
if isempty(stk):
return "underflow"
else:
top=len(stk)-1
return stk[top]
def display(stk):
if isempty(stk):
print('stack is empty')
else:
top=len(stk)-1
print(stk[top],'<-top')
for i in range(top-1,-1,-1):
print(stk[i])
#Driver Code
def main():
stk=[]
top=None
while True:
print('''stack operation
1.push
2.pop
3.peek
4.display
5.exit''')
choice=int (input('enter choice:'))
if choice==1:
item=int(input('enter item:'))
push(stk,item)
elif choice==2:
item=pop(stk)
if item=="underflow":
print('stack is underflow')
else:
print('poped')
elif choice==3:
item=peek(stk)
if item=="underflow":
print('stack is underflow')
else:
print('top most item is:',item)
elif choice==4:
display(stk)
elif choice==5:
break
else:
print('invalid')
exit()
main()
24. Write a program to implement a queue using a list data
structure.
Download
# Function to check Queue is empty or not
def isEmpty(qLst):
if len(qLst)==0:
return 1
else:
return 0
# Function to add elements in Queue
def Enqueue(qLst,val):
qLst.append(val)
if len(qLst)==1:
front=rear=0
else:
rear=len(qLst)-1
# Function to Delete elements in Queue
def Dqueue(qLst):
if isEmpty(qLst):
return "UnderFlow"
else:
val = qLst.pop(0)
if len(qLst)==0:
front=rear=None
return val
# Function to Display top element of Queue
def Peek(qLst):
if isEmpty(qLst):
return "UnderFlow"
else:
front=0
return qLst[front]
# Function to Display elements of Queue
def Display(qLst):
if isEmpty(qLst):
print("No Item to Dispay in Queue....")
else:
tp = len(qLst)-1
print("[FRONT]",end=' ')
front = 0
i = front
rear = len(qLst)-1
while(i<=rear):
print(qLst[i],'<-',end=' ')
i += 1
print()
# Driver function
def main():
qList = []
front = rear = 0
while True:
print()
print("##### QUEUE OPERATION #####")
print("1. ENQUEUE ")
print("2. DEQUEUE ")
print("3. PEEK ")
print("4. DISPLAY ")
print("0. EXIT ")
choice = int(input("Enter Your Choice: "))
if choice == 1:
ele = int(input("Enter element to
insert"))
Enqueue(qList,ele)
elif choice == 2:
val = Dqueue(qList)
if val == "UnderFlow":
print("Queue is Empty")
else:
print("\n Deleted Element was :
",val)
elif choice==3:
val = Peek(qList)
if val == "UnderFlow":
print("Queue is Empty")
else:
print("Item at Front: ",val)
elif choice==4:
Display(qList)
elif choice==0:
print("Good Luck......")
break
main()
25. Write a python program to implement searching methods
based on user choice using a list data-structure. (linear &
binary)
Download
#Linear Search Function Definition
def Linear_Search( lst, srchItem):
found= False
for i in range(len(lst)):
if lst[i] == srchItem:
found = True
print(srchItem, ' was found in the list
at index ', i)
break
if found == False:
print(srchItem, ' was not found in the
list!')
#Binary Search Definition
def binary_Search(Lst,num):
start = 0
end = len(Lst) - 1
mid = (start + end) // 2
# We took found as False that is, initially
# we are considering that the given number
# is not present in the list unless proven
found = False
position = -1
while start <= end:
if Lst[mid] == num:
found = True
position = mid
print('Number %d found at position %d'%
(num, position+1))
break
if num > Lst[mid]:
start = mid + 1
mid = (start + end) // 2
else:
end = mid - 1
mid = (start + end) // 2
if found==False:
print('Number %d not found' %num)
# DRIVER CODE
def main():
print ("SEARCH MENU")
print ("1. LINEAR SERACH")
print ("2. BINARY SEARCH")
print ("3. EXIT")
choice=int(input("Enter your Choice [ 1 - 3 ]:
"))
arr = [12, 34, 54, 2, 3]
n = len(arr)
if choice==1:
print("The List contains : ",arr)
num=int(input("Enter number to be searched:
"))
index = Linear_Search(arr,num)
if choice==2:
arr = [2, 3,12,34,54] #Sorted Array
print("The List contains : ",arr)
num=int(input("Enter number to be searched:
"))
result = binary_Search(arr,num)
main()