0% found this document useful (0 votes)
1 views65 pages

Python Program For Practice

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views65 pages

Python Program For Practice

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Programming Questions and Answers

(Part 1: Q1–Q20)

Questions and Answers


1. Write a Python program to read two integers and print their
sum, difference, product, and quotient.
Answer:
a = int ( input ( " Enter ␣ first ␣ integer : ␣ " ) )
b = int ( input ( " Enter ␣ second ␣ integer : ␣ " ) )

print ( " Sum ␣ = " , a + b )


print ( " Difference ␣ = " , a - b )
print ( " Product ␣ = " , a * b )

if b != 0:
print ( " Quotient ␣ = " , a / b )
else :
print ( " Division ␣ by ␣ zero ␣ not ␣ possible " )

Output:

Enter first integer: 10


Enter second integer: 4
Sum = 14
Difference = 6
Product = 40
Quotient = 2.5

2. Write a Python program to check whether a given number is


even or odd without using the modulus operator.
Answer:

1
2

n = int ( input ( " Enter ␣ a ␣ number : ␣ " ) )

if ( n // 2) * 2 == n :
print ( " Even " )
else :
print ( " Odd " )

Output:

Enter a number: 7
Odd

3. Write a Python program to find the largest of three numbers.


Answer:
a = float ( input ( " Enter ␣ first : ␣ " ) )
b = float ( input ( " Enter ␣ second : ␣ " ) )
c = float ( input ( " Enter ␣ third : ␣ " ) )

largest = a
if b > largest :
largest = b
if c > largest :
largest = c

print ( " Largest ␣ = " , largest )

Output:

Enter first: 12
Enter second: 5
Enter third: 30
Largest = 30.0

4. Write a Python program to check whether a given year is a


leap year.
Answer:
year = int ( input ( " Enter ␣ year : ␣ " ) )

if ( year % 400 == 0) or ( year % 4 == 0 and year %


100 != 0) :
3

print ( " Leap ␣ year " )


else :
print ( " Not ␣ a ␣ leap ␣ year " )

Output:

Enter year: 2024


Leap year

5. Write a Python program to check whether a character is a


vowel or consonant.
Answer:
ch = input ( " Enter ␣ a ␣ character : ␣ " )

if len ( ch ) != 1 or not ch . isalpha () :


print ( " Invalid ␣ input " )
elif ch . lower () in " aeiou " :
print ( " Vowel " )
else :
print ( " Consonant " )

Output:

Enter a character: e
Vowel

6. Write a Python program to compute the factorial of a number


using a loop.
Answer:
n = int ( input ( " Enter ␣ number : ␣ " ) )

if n < 0:
print ( " Factorial ␣ not ␣ defined ␣ for ␣ negative ␣
numbers " )
else :
fact = 1
for i in range (1 , n +1) :
fact *= i
print ( " Factorial ␣ = " , fact )

Output:
4

Enter number: 5
Factorial = 120

7. Write a Python program to generate the first n Fibonacci


numbers.
Answer:
n = int ( input ( " Enter ␣ n : ␣ " ) )

if n <= 0:
print ( " Enter ␣ positive ␣ n " )
else :
a, b = 0, 1
for _ in range ( n ) :
print (a , end = " ␣ " )
a, b = b, a + b

Output:

Enter n: 7
0 1 1 2 3 5 8

8. Write a Python program to check whether a number is prime.


Answer:
n = int ( input ( " Enter ␣ number : ␣ " ) )

if n <= 1:
print ( " Not ␣ prime " )
else :
prime = True
for i in range (2 , int ( n **0.5) +1) :
if n % i == 0:
prime = False
break
print ( " Prime " if prime else " Not ␣ prime " )

Output:

Enter number: 29
Prime
5

9. Write a Python program to print all prime numbers between


two integers.
Answer:
start = int ( input ( " Start : ␣ " ) )
end = int ( input ( " End : ␣ " ) )

for n in range ( start , end +1) :


if n > 1:
for i in range (2 , int ( n **0.5) +1) :
if n % i == 0:
break
else :
print (n , end = " ␣ " )

Output:

Start: 10
End: 30
11 13 17 19 23 29

10. Write a Python program to reverse the digits of an integer


without converting it to a string.
Answer:
n = int ( input ( " Enter ␣ number : ␣ " ) )
rev = 0
temp = n

while temp != 0:
digit = temp % 10
rev = rev * 10 + digit
temp //= 10

print ( " Reversed ␣ = " , rev )

Output:

Enter number: 12340


Reversed = 4321

11. Write a Python program to check whether a number is a palin-


drome.
Answer:
6

n = int ( input ( " Enter ␣ number : ␣ " ) )


temp = n
rev = 0

while temp != 0:
rev = rev *10 + temp %10
temp //= 10

print ( " Palindrome " if rev == n else " Not ␣ palindrome "
)

Output:

Enter number: 1221


Palindrome

12. Write a Python program to check whether a number is an


Armstrong number.
Answer:
n = int ( input ( " Enter ␣ number : ␣ " ) )
s = str ( n )
power = len ( s )

total = 0
for d in s :
total += int ( d ) ** power

print ( " Armstrong " if total == n else " Not ␣ Armstrong "
)

Output:

Enter number: 153


Armstrong

13. Write a Python program to compute the sum of digits of an


integer.
Answer:
7

n = int ( input ( " Enter ␣ number : ␣ " ) )


s = 0
temp = n

while temp != 0:
s += temp % 10
temp //= 10

print ( " Sum ␣ of ␣ digits ␣ = " , s )

Output:

Enter number: 987


Sum of digits = 24

14. Write a Python program to find the GCD of two numbers


using the Euclidean algorithm.
Answer:
a = int ( input ( " Enter ␣ a : ␣ " ) )
b = int ( input ( " Enter ␣ b : ␣ " ) )

while b != 0:
a, b = b, a % b

print ( " GCD ␣ = " , a )

Output:

Enter a: 36
Enter b: 60
GCD = 12

15. Write a Python program to find the LCM of two integers.


Answer:
a = int ( input ( " Enter ␣ a : ␣ " ) )
b = int ( input ( " Enter ␣ b : ␣ " ) )

if a == 0 or b == 0:
print ( " LCM ␣ = ␣ 0 " )
else :
8

x, y = a, b
while y != 0:
x, y = y, x % y
gcd = x
lcm = abs ( a * b ) // gcd
print ( " LCM ␣ = " , lcm )

Output:

Enter a: 12
Enter b: 18
LCM = 36

16. Write a Python program to print the multiplication table of


a number.
Answer:
n = int ( input ( " Enter ␣ number : ␣ " ) )

for i in range (1 , 11) :


print (n , " x " , i , " = " , n * i )

Output:

Enter number: 7
7 x 1 = 7
7 x 2 = 14
...
7 x 10 = 70

17. Write a Python program to print all factors of a number.


Answer:
n = int ( input ( " Enter ␣ number : ␣ " ) )

if n <= 0:
print ( " Enter ␣ positive ␣ number " )
else :
for i in range (1 , n +1) :
if n % i == 0:
print (i , end = " ␣ " )

Output:
9

Enter number: 12
1 2 3 4 6 12

18. Write a Python program to count the number of digits in an


integer.
Answer:
n = int ( input ( " Enter ␣ number : ␣ " ) )
temp = abs ( n )
count = 0

if temp == 0:
count = 1
else :
while temp > 0:
temp //= 10
count += 1

print ( " Digits ␣ = " , count )

Output:

Enter number: -12345


Digits = 5

19. Write a Python program to convert a decimal number to bi-


nary without using built-in functions.
Answer:
n = int ( input ( " Enter ␣ number : ␣ " ) )

if n == 0:
print ( " Binary ␣ = ␣ 0 " )
else :
bits = []
temp = n
while temp > 0:
bits . append ( str ( temp % 2) )
temp //= 2
bits . reverse ()
print ( " Binary ␣ = " , " " . join ( bits ) )

Output:
10

Enter number: 13
Binary = 1101

20. Write a Python program to convert a binary string to decimal.


Answer:
b = input ( " Enter ␣ binary : ␣ " ) . strip ()

valid = all ( ch in " 01 " for ch in b )

if not valid or b == " " :


print ( " Invalid ␣ binary " )
else :
decimal = 0
for ch in b :
decimal = decimal * 2 + int ( ch )
print ( " Decimal ␣ = " , decimal )

Output:

Enter binary: 10101


Decimal = 21
Python Programming Questions and Answers
(Part 6: Q101–Q120)

Questions and Answers


1. Write a Python program to implement a menu-driven calcu-
lator using functions.
Answer:
def add (a , b ) : return a+b
def sub (a , b ) : return a-b
def mul (a , b ) : return a*b
def div (a , b ) : return a / b if b !=0 else " Error "

print ( " 1. Add ␣ 2. Sub ␣ 3. Mul ␣ 4. Div " )


ch = int ( input ( " Enter ␣ choice : ␣ " ) )
a = float ( input ( " Enter ␣ a : ␣ " ) )
b = float ( input ( " Enter ␣ b : ␣ " ) )

if ch ==1: print ( add (a , b ) )


elif ch ==2: print ( sub (a , b ) )
elif ch ==3: print ( mul (a , b ) )
elif ch ==4: print ( div (a , b ) )
else : print ( " Invalid " )

Output:

[Link] [Link] [Link] [Link]


Enter choice: 1
Enter a: 10
Enter b: 5
15

2. Write a Python program to simulate a grading system for n


students.

1
2

Answer:
n = int ( input ( " Enter ␣ number ␣ of ␣ students : ␣ " ) )

for i in range ( n ) :
m = int ( input ( " Enter ␣ marks : ␣ " ) )
if m >=90: g = " A "
elif m >=75: g = " B "
elif m >=60: g = " C "
else : g = " D "
print ( " Grade : " , g )

Output:

Enter number of students: 3


Enter marks: 92
Grade: A
Enter marks: 70
Grade: C
Enter marks: 55
Grade: D

3. Write a Python program to generate Pascal’s triangle up to


n rows.
Answer:
n = int ( input ( " Enter ␣ n : ␣ " ) )

for i in range ( n ) :
num = 1
for j in range ( i +1) :
print ( num , end = " ␣ " )
num = num * (i - j ) // ( j +1)
print ()

Output:

Enter n: 5
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
3

4. Write a Python program to generate all permutations of a


string.
Answer:
def permute (s , ans = " " ) :
if len ( s ) ==0:
print ( ans )
else :
for i in range ( len ( s ) ) :
permute ( s [: i ]+ s [ i +1:] , ans + s [ i ])

s = input ( " Enter ␣ string : ␣ " )


permute ( s )

Output:

Enter string: abc


abc
acb
bac
bca
cab
cba

5. Write a Python program to compute the sum of the series 1


+ 1/2² + ... + 1/n².
Answer:
n = int ( input ( " Enter ␣ n : ␣ " ) )
s = 0

for i in range (1 , n +1) :


s += 1/( i * i )

print ( " Sum ␣ = " , s )

Output:

Enter n: 5
Sum = 1.463611...

6. Write a Python program to print all Pythagorean triplets with


c limit.
Answer:
4

limit = int ( input ( " Enter ␣ limit : ␣ " ) )

for a in range (1 , limit ) :


for b in range (a , limit ) :
c = ( a * a + b * b ) **0.5
if c . is_integer () and c <= limit :
print (a , b , int ( c ) )

Output:

Enter limit: 20
3 4 5
5 12 13
8 15 17

7. Write a Python program to simulate a contact book using a


dictionary.
Answer:
contacts = {}

while True :
print ( " 1. Add ␣ 2. Search ␣ 3. Update ␣ 4. Delete ␣ 5. Exit " )
ch = int ( input ( " Choice : ␣ " ) )

if ch ==1:
name = input ( " Name : ␣ " )
num = input ( " Number : ␣ " )
contacts [ name ] = num

elif ch ==2:
name = input ( " Name : ␣ " )
print ( contacts . get ( name , " Not ␣ found " ) )

elif ch ==3:
name = input ( " Name : ␣ " )
if name in contacts :
contacts [ name ] = input ( " New ␣ number : ␣ " )

elif ch ==4:
name = input ( " Name : ␣ " )
contacts . pop ( name , None )
5

else :
break

Output:

[Link] [Link] [Link] [Link] [Link]


...

8. Write a Python program to partition a list into negative, zero,


and positive lists.
Answer:
lst = list ( map ( int , input ( " Enter ␣ list : ␣ " ) . split () ) )

neg = [ x for x in lst if x <0]


zero = [ x for x in lst if x ==0]
pos = [ x for x in lst if x >0]

print ( neg )
print ( zero )
print ( pos )

Output:

Enter list: -3 0 5 -1 2 0
[-3, -1]
[0, 0]
[5, 2]

9. Write a Python program to perform matrix addition and mul-


tiplication.
Answer:
A = eval ( input ( " Enter ␣ matrix ␣ A : ␣ " ) )
B = eval ( input ( " Enter ␣ matrix ␣ B : ␣ " ) )

add = [[ A [ i ][ j ] + B [ i ][ j ] for j in range ( len ( A [0]) ) ]


for i in range ( len ( A ) ) ]

mul = [[ sum ( A [ i ][ k ]* B [ k ][ j ] for k in range ( len ( B ) ) )


for j in range ( len ( B [0]) ) ]
6

for i in range ( len ( A ) ) ]

print ( " Addition : " , add )


print ( " Multiplication : " , mul )

Output:

Enter matrix A: [[1,2],[3,4]]


Enter matrix B: [[5,6],[7,8]]
Addition: [[6, 8], [10, 12]]
Multiplication: [[19, 22], [43, 50]]

10. Write a Python program to compute the determinant of 2×2


and 3×3 matrices.
Answer:
import numpy as np

mat = eval ( input ( " Enter ␣ matrix : ␣ " ) )


det = np . linalg . det ( np . array ( mat ) )

print ( " Determinant ␣ = " , det )

Output:

Enter matrix: [[1,2],[3,4]]


Determinant = -2.0

11. Write a Python program for a number guessing game.


Answer:
import random

num = random . randint (1 , 50)

for i in range (5) :


g = int ( input ( " Guess : ␣ " ) )
if g == num :
print ( " Correct ! " )
break
elif g < num :
print ( " Too ␣ low " )
7

else :
print ( " Too ␣ high " )
else :
print ( " Number ␣ was " , num )

Output:

Guess: 20
Too low
...

12. Write a Python program to simulate rolling two dice 1000


times and display frequency of sums.
Answer:
import random

freq = { i :0 for i in range (2 ,13) }

for _ in range (1000) :


s = random . randint (1 ,6) + random . randint (1 ,6)
freq [ s ] += 1

print ( freq )

Output:

{2: 28, 3: 55, ..., 12: 30}

13. Write a Python program to remove all elements that appear


more than once in a list.
Answer:
lst = input ( " Enter ␣ list : ␣ " ) . split ()

result = [ x for x in lst if lst . count ( x ) ==1]


print ( result )

Output:

Enter list: a b a c d d e
[’b’, ’c’, ’e’]
8

14. Write a Python program to group words by their length.


Answer:
words = input ( " Enter ␣ words : ␣ " ) . split ()

d = {}
for w in words :
d . setdefault ( len ( w ) , []) . append ( w )

print ( d )

Output:

Enter words: cat dog apple hi


{3: [’cat’, ’dog’], 5: [’apple’], 2: [’hi’]}

15. Write a Python program to implement a command-line to-do


list.
Answer:
todo = []

while True :
print ( " 1. Add ␣ 2. View ␣ 3. Remove ␣ 4. Exit " )
ch = int ( input ( " Choice : ␣ " ) )

if ch ==1:
todo . append ( input ( " Task : ␣ " ) )
elif ch ==2:
print ( todo )
elif ch ==3:
task = input ( " Task ␣ to ␣ remove : ␣ " )
if task in todo :
todo . remove ( task )
else :
break

Output:

[Link] [Link] [Link] [Link]


...
9

16. Write a Python program to compress a string using run-length


encoding.
Answer:
s = input ( " Enter ␣ string : ␣ " )

res = " "


i = 0
while i < len ( s ) :
count = 1
while i +1 < len ( s ) and s [ i ]== s [ i +1]:
count += 1
i += 1
res += s [ i ] + str ( count )
i += 1

print ( res )

Output:

Enter string: aaabbc


a3b2c1

17. Write a Python program to validate a password.


Answer:
import string

pwd = input ( " Enter ␣ password : ␣ " )

valid = (
len ( pwd ) >=8 and
any ( c . isupper () for c in pwd ) and
any ( c . islower () for c in pwd ) and
any ( c . isdigit () for c in pwd ) and
any ( c in string . punctuation for c in pwd )
)

print ( " Valid " if valid else " Invalid " )

Output:

Enter password: Abc@1234


Valid
10

18. Write a Python program to validate a date in DD/MM/YYYY


format.
Answer:
d , m , y = map ( int , input ( " Enter ␣ date ␣ ( DD / MM / YYYY ) : ␣ "
) . split ( " / " ) )

valid = True

if m <1 or m >12:
valid = False
elif d <1 or d >31:
valid = False
elif m in [4 ,6 ,9 ,11] and d >30:
valid = False
elif m ==2:
leap = ( y %400==0) or ( y %4==0 and y %100!=0)
if ( leap and d >29) or ( not leap and d >28) :
valid = False

print ( " Valid " if valid else " Invalid " )

Output:

Enter date (DD/MM/YYYY): 29/02/2024


Valid

19. Write a Python program to simulate an inventory system us-


ing a dictionary.
Answer:
inv = {}

while True :
print ( " 1. Add ␣ 2. Update ␣ 3. Display ␣ 4. Exit " )
ch = int ( input ( " Choice : ␣ " ) )

if ch ==1:
item = input ( " Item : ␣ " )
qty = int ( input ( " Qty : ␣ " ) )
price = float ( input ( " Price : ␣ " ) )
inv [ item ] = [ qty , price ]
11

elif ch ==2:
item = input ( " Item : ␣ " )
if item in inv :
inv [ item ][0] = int ( input ( " New ␣ qty : ␣ " ) )
inv [ item ][1] = float ( input ( " New ␣ price : ␣ "
))

elif ch ==3:
print ( inv )

else :
break

Output:

[Link] [Link] [Link] [Link]


...

20. Write a Python program to summarize log levels (INFO, WARN-


ING, ERROR) in a log file.
Answer:
filename = input ( " Enter ␣ log ␣ file : ␣ " )

counts = { " INFO " :0 , " WARNING " :0 , " ERROR " :0}

with open ( filename , " r " ) as f :


for line in f :
for level in counts :
if level in line :
counts [ level ] += 1

print ( counts )

Output:

{’INFO’: 12, ’WARNING’: 3, ’ERROR’: 1}


Python Programming Questions and Answers
(Part 5: Q81–Q100)

Questions and Answers


1. Write a Python program to read a text file and count the
number of lines, words, and characters.
Answer:
filename = input ( " Enter ␣ filename : ␣ " )

with open ( filename , " r " ) as f :


text = f . read ()

lines = text . count ( " \ n " ) + 1


words = len ( text . split () )
chars = len ( text )

print ( " Lines : " , lines )


print ( " Words : " , words )
print ( " Characters : " , chars )

Output:

Lines: 5
Words: 20
Characters: 110

2. Write a Python program to print only the lines from a file


that contain a given substring.
Answer:
filename = input ( " Enter ␣ filename : ␣ " )
sub = input ( " Enter ␣ substring : ␣ " )

1
2

with open ( filename , " r " ) as f :


for line in f :
if sub in line :
print ( line , end = " " )

Output:

(Displays only matching lines)

3. Write a Python program to copy the contents of one file to


another.
Answer:
src = input ( " Source ␣ file : ␣ " )
dst = input ( " Destination ␣ file : ␣ " )

with open ( src , " r " ) as f1 , open ( dst , " w " ) as f2 :


f2 . write ( f1 . read () )

print ( " File ␣ copied . " )

Output:

File copied.

4. Write a Python program to read a file and display word fre-


quencies in sorted order.
Answer:
filename = input ( " Enter ␣ filename : ␣ " )

with open ( filename , " r " ) as f :


words = f . read () . split ()

freq = {}
for w in words :
freq [ w ] = freq . get (w , 0) + 1

for k in sorted ( freq , key = freq . get , reverse = True ) :


print (k , " : " , freq [ k ])

Output:
3

word1 : 5
word2 : 3
word3 : 1

5. Write a Python program to append text to a file and display


the updated contents.
Answer:
filename = input ( " Enter ␣ filename : ␣ " )
text = input ( " Enter ␣ text ␣ to ␣ append : ␣ " )

with open ( filename , " a " ) as f :


f . write ( " \ n " + text )

with open ( filename , " r " ) as f :


print ( f . read () )

Output:

(Displays updated file contents)

6. Write a Python program to read a CSV file of student marks


and print the student with the highest total.
Answer:
import csv

filename = input ( " Enter ␣ CSV ␣ filename : ␣ " )

max_total = -1
top_student = " "

with open ( filename , " r " ) as f :


reader = csv . reader ( f )
for row in reader :
name = row [0]
marks = list ( map ( int , row [1:]) )
total = sum ( marks )
if total > max_total :
max_total = total
top_student = name

print ( " Top ␣ student : " , top_student , " Total : " ,


max_total )
4

Output:

Top student: Ram Total: 275

7. Write a Python program to remove blank lines from a text


file.
Answer:
src = input ( " Source ␣ file : ␣ " )
dst = input ( " Destination ␣ file : ␣ " )

with open ( src , " r " ) as f1 , open ( dst , " w " ) as f2 :


for line in f1 :
if line . strip () :
f2 . write ( line )

print ( " Blank ␣ lines ␣ removed . " )

Output:

Blank lines removed.

8. Write a Python program to print the longest line in a file.


Answer:
filename = input ( " Enter ␣ filename : ␣ " )

with open ( filename , " r " ) as f :


lines = f . readlines ()

longest = max ( lines , key = len )

print ( " Longest ␣ line : " , longest )


print ( " Length : " , len ( longest ) )

Output:

Longest line: This is the longest line.


Length: 27

9. Write a Python program to count occurrences of a word in a


file (case-insensitive).
Answer:
5

filename = input ( " Enter ␣ filename : ␣ " )


word = input ( " Enter ␣ word : ␣ " ) . lower ()

with open ( filename , " r " ) as f :


text = f . read () . lower ()

print ( " Count ␣ = " , text . split () . count ( word ) )

Output:

Count = 4

10. Write a Python program to merge two files line by line into a
third file.
Answer:
f1 = open ( input ( " File ␣ 1: ␣ " ) , " r " )
f2 = open ( input ( " File ␣ 2: ␣ " ) , " r " )
f3 = open ( input ( " Output ␣ file : ␣ " ) , " w " )

for a , b in zip ( f1 , f2 ) :
f3 . write ( a . strip () + " ␣ " + b )

f1 . close ()
f2 . close ()
f3 . close ()

print ( " Merged . " )

Output:

Merged.

11. Write a Python program to define a Rectangle class with area


and perimeter methods.
Answer:
class Rectangle :
def __init__ ( self , l , b ) :
self . l = l
self . b = b
6

def area ( self ) :


return self . l * self . b

def perimeter ( self ) :


return 2 * ( self . l + self . b )

r = Rectangle (5 , 3)
print ( " Area : " , r . area () )
print ( " Perimeter : " , r . perimeter () )

Output:

Area: 15
Perimeter: 16

12. Write a Python program to define a BankAccount class with


deposit, withdraw, and display methods.
Answer:
class BankAccount :
def __init__ ( self , bal =0) :
self . bal = bal

def deposit ( self , amt ) :


self . bal += amt

def withdraw ( self , amt ) :


if amt <= self . bal :
self . bal -= amt
else :
print ( " Insufficient ␣ balance " )

def display ( self ) :


print ( " Balance : " , self . bal )

acc = BankAccount (1000)


acc . deposit (500)
acc . withdraw (300)
acc . display ()

Output:

Balance: 1200
7

13. Write a Python program to define a Student class with total


and grade calculation.
Answer:
class Student :
def __init__ ( self , name , m1 , m2 , m3 ) :
self . name = name
self . m1 = m1
self . m2 = m2
self . m3 = m3

def total ( self ) :


return self . m1 + self . m2 + self . m3

def grade ( self ) :


avg = self . total () / 3
if avg >= 90: return " A "
elif avg >= 75: return " B "
elif avg >= 60: return " C "
else : return " D "

s = Student ( " Ram " , 85 , 90 , 80)


print ( " Total : " , s . total () )
print ( " Grade : " , s . grade () )

Output:

Total: 255
Grade: B

14. Write a Python program to implement a ComplexNumber


class with addition and subtraction.
Answer:
class Complex :
def __init__ ( self , r , i ) :
self . r = r
self . i = i

def add ( self , other ) :


return Complex ( self . r + other .r , self . i +
other . i )
8

def sub ( self , other ) :


return Complex ( self . r - other .r , self . i -
other . i )

def __str__ ( self ) :


return f " { self . r }+{ self . i } i "

c1 = Complex (3 , 4)
c2 = Complex (1 , 2)

print ( " Sum : " , c1 . add ( c2 ) )


print ( " Difference : " , c1 . sub ( c2 ) )

Output:

Sum: 4+6i
Difference: 2+2i

15. Write a Python program to demonstrate single inheritance.


Answer:
class Person :
def __init__ ( self , name ) :
self . name = name

class Employee ( Person ) :


def __init__ ( self , name , salary ) :
super () . __init__ ( name )
self . salary = salary

e = Employee ( " Ram " , 50000)


print ( e . name , e . salary )

Output:

Ram 50000

16. Write a Python program to demonstrate method overriding


using Shape, Circle, and Rectangle classes.
Answer:
9

class Shape :
def area ( self ) :
return 0

class Circle ( Shape ) :


def __init__ ( self , r ) :
self . r = r
def area ( self ) :
return 3.14 * self . r * self . r

class Rectangle ( Shape ) :


def __init__ ( self , l , b ) :
self . l = l
self . b = b
def area ( self ) :
return self . l * self . b

print ( " Circle ␣ area : " , Circle (5) . area () )


print ( " Rectangle ␣ area : " , Rectangle (4 , 6) . area () )

Output:

Circle area: 78.5


Rectangle area: 24

17. Write a Python program to implement a Stack class using a


list.
Answer:
class Stack :
def __init__ ( self ) :
self . s = []

def push ( self , x ) :


self . s . append ( x )

def pop ( self ) :


if self . s :
return self . s . pop ()
return " Empty "

def peek ( self ) :


10

return self . s [ -1] if self . s else " Empty "

st = Stack ()
st . push (10)
st . push (20)
print ( st . pop () )
print ( st . peek () )

Output:

20
10

18. Write a Python program to implement a Queue class using a


list.
Answer:
class Queue :
def __init__ ( self ) :
self . q = []

def enqueue ( self , x ) :


self . q . append ( x )

def dequeue ( self ) :


if self . q :
return self . q . pop (0)
return " Empty "

qu = Queue ()
qu . enqueue (10)
qu . enqueue (20)
print ( qu . dequeue () )
print ( qu . dequeue () )

Output:

10
20

19. Write a Python program to demonstrate operator overloading


for a Vector2D class.
Answer:
11

class Vector2D :
def __init__ ( self , x , y ) :
self . x = x
self . y = y

def __add__ ( self , other ) :


return Vector2D ( self . x + other .x , self . y +
other . y )

def __eq__ ( self , other ) :


return self . x == other . x and self . y == other
.y

def __str__ ( self ) :


return f " ({ self . x } ,{ self . y }) "

v1 = Vector2D (1 , 2)
v2 = Vector2D (3 , 4)

print ( v1 + v2 )
print ( v1 == v2 )

Output:

(4,6)
False

20. Write a Python program to implement a Library class that


manages book titles.
Answer:
class Library :
def __init__ ( self ) :
self . books = []

def add ( self , title ) :


self . books . append ( title )

def remove ( self , title ) :


if title in self . books :
self . books . remove ( title )
12

def search ( self , title ) :


return title in self . books

lib = Library ()
lib . add ( " Python " )
lib . add ( " AI " )
print ( lib . search ( " Python " ) )
lib . remove ( " Python " )
print ( lib . search ( " Python " ) )

Output:

True
False
Python Programming Questions and Answers
(Part 4: Q61–Q80)

Questions and Answers


1. Write a Python program to create a dictionary from user in-
put (key–value pairs).
Answer:
n = int ( input ( " Enter ␣ number ␣ of ␣ pairs : ␣ " ) )
d = {}

for i in range ( n ) :
key = input ( " Key : ␣ " )
value = input ( " Value : ␣ " )
d [ key ] = value

print ( d )

Output:

Enter number of pairs: 3


Key: a
Value: 1
Key: b
Value: 2
Key: c
Value: 3
{’a’: ’1’, ’b’: ’2’, ’c’: ’3’}

2. Write a Python program to count the frequency of words in


a sentence using a dictionary.
Answer:

1
2

s = input ( " Enter ␣ sentence : ␣ " ) . split ()

freq = {}
for w in s :
freq [ w ] = freq . get (w , 0) + 1

print ( freq )

Output:

Enter sentence: this is a test this is


{’this’: 2, ’is’: 2, ’a’: 1, ’test’: 1}

3. Write a Python program to find the key with the maximum


value in a dictionary.
Answer:
d = eval ( input ( " Enter ␣ dictionary : ␣ " ) )

max_key = max (d , key = d . get )


print ( " Key ␣ with ␣ max ␣ value : " , max_key )

Output:

Enter dictionary: {’a’:10,’b’:25,’c’:15}


Key with max value: b

4. Write a Python program to invert a dictionary (swap keys


and values).
Answer:
d = eval ( input ( " Enter ␣ dictionary : ␣ " ) )

inv = { v : k for k , v in d . items () }


print ( inv )

Output:

Enter dictionary: {’a’:1,’b’:2,’c’:3}


{1: ’a’, 2: ’b’, 3: ’c’}
3

5. Write a Python program to merge two dictionaries and sum


values of common keys.
Answer:
d1 = eval ( input ( " Enter ␣ dict ␣ 1: ␣ " ) )
d2 = eval ( input ( " Enter ␣ dict ␣ 2: ␣ " ) )

merged = d1 . copy ()

for k , v in d2 . items () :
merged [ k ] = merged . get (k , 0) + v

print ( merged )

Output:

Enter dict 1: {’a’:1,’b’:2}


Enter dict 2: {’b’:3,’c’:4}
{’a’: 1, ’b’: 5, ’c’: 4}

6. Write a Python program to remove a key from a dictionary if


it exists.
Answer:
d = eval ( input ( " Enter ␣ dictionary : ␣ " ) )
key = input ( " Enter ␣ key ␣ to ␣ remove : ␣ " )

if key in d :
del d [ key ]

print ( d )

Output:

Enter dictionary: {’a’:1,’b’:2,’c’:3}


Enter key to remove: b
{’a’: 1, ’c’: 3}

7. Write a Python program to sort a dictionary by keys.


Answer:
4

d = eval ( input ( " Enter ␣ dictionary : ␣ " ) )

sorted_dict = dict ( sorted ( d . items () ) )


print ( sorted_dict )

Output:

Enter dictionary: {’c’:3,’a’:1,’b’:2}


{’a’: 1, ’b’: 2, ’c’: 3}

8. Write a Python program to sort a dictionary by values.


Answer:
d = eval ( input ( " Enter ␣ dictionary : ␣ " ) )

sorted_dict = dict ( sorted ( d . items () , key = lambda x : x


[1]) )
print ( sorted_dict )

Output:

Enter dictionary: {’a’:3,’b’:1,’c’:2}


{’b’: 1, ’c’: 2, ’a’: 3}

9. Write a Python program to check whether a given key exists


in a dictionary.
Answer:
d = eval ( input ( " Enter ␣ dictionary : ␣ " ) )
key = input ( " Enter ␣ key : ␣ " )

print ( " Exists " if key in d else " Does ␣ not ␣ exist " )

Output:

Enter dictionary: {’a’:1,’b’:2}


Enter key: b
Exists

10. Write a Python program to create a nested dictionary of stu-


dents and marks, then print totals.
Answer:
5

students = eval ( input ( " Enter ␣ nested ␣ dictionary : ␣ " ) )

for name , marks in students . items () :


total = sum ( marks . values () )
print ( name , " Total : " , total )

Output:

Enter nested dictionary: {’Ram’:{’m1’:50,’m2’:60}, ’Sam’:{’m1’:40,’m2’:70}}


Ram Total: 110
Sam Total: 110

11. Write a Python function to compute factorial using recursion.


Answer:
def fact ( n ) :
if n == 0:
return 1
return n * fact (n -1)

n = int ( input ( " Enter ␣ number : ␣ " ) )


print ( " Factorial ␣ = " , fact ( n ) )

Output:

Enter number: 5
Factorial = 120

12. Write a Python function to compute the nth Fibonacci num-


ber using recursion.
Answer:
def fib ( n ) :
if n <= 1:
return n
return fib (n -1) + fib (n -2)

n = int ( input ( " Enter ␣ n : ␣ " ) )


print ( " Fibonacci ␣ = " , fib ( n ) )

Output:
6

Enter n: 6
Fibonacci = 8

13. Write a Python program using a function to print all primes


in a range.
Answer:
def is_prime ( n ) :
if n <= 1:
return False
for i in range (2 , int ( n **0.5) +1) :
if n % i == 0:
return False
return True

start = int ( input ( " Start : ␣ " ) )


end = int ( input ( " End : ␣ " ) )

for n in range ( start , end +1) :


if is_prime ( n ) :
print (n , end = " ␣ " )

Output:

Start: 10
End: 20
11 13 17 19

14. Write a Python function that returns the greatest of three


numbers.
Answer:
def greatest (a , b , c ) :
return max (a , b , c )

a = int ( input () )
b = int ( input () )
c = int ( input () )

print ( " Greatest ␣ = " , greatest (a , b , c ) )

Output:
7

10
25
7
Greatest = 25

15. Write a Python function that returns a list of unique elements.


Answer:
def unique ( lst ) :
u = []
for x in lst :
if x not in u :
u . append ( x )
return u

lst = input ( " Enter ␣ list : ␣ " ) . split ()


print ( unique ( lst ) )

Output:

Enter list: a b a c b
[’a’, ’b’, ’c’]

16. Write a Python function that counts vowels in a string.


Answer:
def count_vowels ( s ) :
return sum (1 for ch in s if ch . lower () in " aeiou
")

s = input ( " Enter ␣ string : ␣ " )


print ( " Vowels ␣ = " , count_vowels ( s ) )

Output:

Enter string: education


Vowels = 5

17. Write a Python function that returns mean, median, and


mode of a list.
Answer:
8

def stats ( lst ) :


lst = sorted ( lst )
n = len ( lst )

mean = sum ( lst ) / n


median = lst [ n //2] if n % 2 == 1 else ( lst [ n
//2 -1] + lst [ n //2]) / 2

mode = max ( lst , key = lst . count )

return mean , median , mode

lst = list ( map ( int , input ( " Enter ␣ list : ␣ " ) . split () ) )
print ( stats ( lst ) )

Output:

Enter list: 1 2 2 3 4
(2.4, 2, 2)

18. Write a Python function to check whether a string is a palin-


drome ignoring spaces and punctuation.
Answer:
def clean ( s ) :
return " " . join ( ch . lower () for ch in s if ch .
isalnum () )

s = input ( " Enter ␣ string : ␣ " )


cs = clean ( s )

print ( " Palindrome " if cs == cs [:: -1] else " Not ␣


palindrome " )

Output:

Enter string: A man, a plan, a canal: Panama


Palindrome

19. Write a Python function that returns all indices of a target


value in a list.
Answer:
9

def find_indices ( lst , target ) :


return [ i for i , x in enumerate ( lst ) if x ==
target ]

lst = input ( " Enter ␣ list : ␣ " ) . split ()


target = input ( " Enter ␣ target : ␣ " )

print ( find_indices ( lst , target ) )

Output:

Enter list: a b c a d a
Enter target: a
[0, 3, 5]

20. Write a Python function to return the transpose of a matrix.


Answer:
matrix = eval ( input ( " Enter ␣ matrix : ␣ " ) )

transpose = []
for col in range ( len ( matrix [0]) ) :
row = []
for r in matrix :
row . append ( r [ col ])
transpose . append ( row )

print ( transpose )

Output:

Enter matrix: [[1,2,3],[4,5,6]]


[[1, 4], [2, 5], [3, 6]]
Python Programming Questions and Answers
(Part 3: Q41–Q60)

Questions and Answers


1. Write a Python program to count vowels, consonants, digits,
and spaces in a string.
Answer:
s = input ( " Enter ␣ string : ␣ " )

vowels = consonants = digits = spaces = 0

for ch in s :
if ch . isdigit () :
digits += 1
elif ch . isspace () :
spaces += 1
elif ch . isalpha () :
if ch . lower () in " aeiou " :
vowels += 1
else :
consonants += 1

print ( " Vowels : " , vowels )


print ( " Consonants : " , consonants )
print ( " Digits : " , digits )
print ( " Spaces : " , spaces )

Output:

Enter string: Hello World 123


Vowels: 3
Consonants: 7

1
2

Digits: 3
Spaces: 2

2. Write a Python program to reverse a string without using


slicing.
Answer:
s = input ( " Enter ␣ string : ␣ " )
rev = " "

for ch in s :
rev = ch + rev

print ( " Reversed : " , rev )

Output:

Enter string: python


Reversed: nohtyp

3. Write a Python program to check whether a string is a palin-


drome (case-insensitive).
Answer:
s = input ( " Enter ␣ string : ␣ " ) . lower ()

rev = " "


for ch in s :
rev = ch + rev

print ( " Palindrome " if s == rev else " Not ␣ palindrome "
)

Output:

Enter string: Madam


Palindrome

4. Write a Python program to count the frequency of each char-


acter in a string.
Answer:
3

s = input ( " Enter ␣ string : ␣ " )

freq = {}
for ch in s :
if ch in freq :
freq [ ch ] += 1
else :
freq [ ch ] = 1

print ( freq )

Output:

Enter string: banana


{’b’: 1, ’a’: 3, ’n’: 2}

5. Write a Python program to remove all occurrences of a sub-


string from a string.
Answer:
s = input ( " Enter ␣ string : ␣ " )
sub = input ( " Enter ␣ substring : ␣ " )

result = s . replace ( sub , " " )


print ( result )

Output:

Enter string: abcabcabc


Enter substring: abc

6. Write a Python program to find the longest word in a sen-


tence.
Answer:
s = input ( " Enter ␣ sentence : ␣ " )
words = s . split ()

longest = words [0]


for w in words :
if len ( w ) > len ( longest ) :
longest = w
4

print ( " Longest ␣ word : " , longest )

Output:

Enter sentence: Python is a powerful language


Longest word: powerful

7. Write a Python program to remove duplicate characters from


a string while preserving order.
Answer:
s = input ( " Enter ␣ string : ␣ " )

result = " "


for ch in s :
if ch not in result :
result += ch

print ( result )

Output:

Enter string: programming


progamin

8. Write a Python program to check whether two strings are


anagrams.
Answer:
s1 = input ( " Enter ␣ first : ␣ " )
s2 = input ( " Enter ␣ second : ␣ " )

print ( " Anagram " if sorted ( s1 ) == sorted ( s2 ) else "


Not ␣ anagram " )

Output:

Enter first: listen


Enter second: silent
Anagram
5

9. Write a Python program to find the first non-repeating char-


acter in a string.
Answer:
s = input ( " Enter ␣ string : ␣ " )

for ch in s :
if s . count ( ch ) == 1:
print ( " First ␣ non - repeating : " , ch )
break
else :
print ( " No ␣ unique ␣ character " )

Output:

Enter string: swiss


First non-repeating: w

10. Write a Python program to replace multiple spaces with a


single space.
Answer:
s = input ( " Enter ␣ string : ␣ " )

result = " ␣ " . join ( s . split () )


print ( result )

Output:

Enter string: Python is great


Python is great

11. Write a Python program to read n integers into a tuple and


find the maximum and minimum.
Answer:
n = int ( input ( " Enter ␣ n : ␣ " ) )
t = []

for i in range ( n ) :
t . append ( int ( input () ) )

t = tuple ( t )
6

print ( " Max ␣ = " , max ( t ) )


print ( " Min ␣ = " , min ( t ) )

Output:

Enter n: 4
10
3
25
7
Max = 25
Min = 3

12. Write a Python program to convert a list to a tuple and a


tuple to a list.
Answer:
lst = input ( " Enter ␣ list : ␣ " ) . split ()
tpl = tuple ( lst )

print ( " Tuple : " , tpl )


print ( " List : " , list ( tpl ) )

Output:

Enter list: a b c
Tuple: (’a’, ’b’, ’c’)
List: [’a’, ’b’, ’c’]

13. Write a Python program to find the index of an element in a


tuple.
Answer:
t = tuple ( input ( " Enter ␣ tuple : ␣ " ) . split () )
x = input ( " Enter ␣ element : ␣ " )

if x in t :
print ( " Index ␣ = " , t . index ( x ) )
else :
print ( " Not ␣ found " )

Output:
7

Enter tuple: a b c d
Enter element: c
Index = 2

14. Write a Python program to count occurrences of each element


in a tuple.
Answer:
t = tuple ( input ( " Enter ␣ tuple : ␣ " ) . split () )

freq = {}
for x in t :
freq [ x ] = freq . get (x , 0) + 1

print ( freq )

Output:

Enter tuple: a b a c b
{’a’: 2, ’b’: 2, ’c’: 1}

15. Write a Python program to concatenate two tuples.


Answer:
t1 = tuple ( input ( " Enter ␣ tuple ␣ 1: ␣ " ) . split () )
t2 = tuple ( input ( " Enter ␣ tuple ␣ 2: ␣ " ) . split () )

print ( " Concatenated : " , t1 + t2 )

Output:

Enter tuple 1: 1 2 3
Enter tuple 2: 4 5
Concatenated: (’1’, ’2’, ’3’, ’4’, ’5’)

16. Write a Python program to slice a tuple based on start and


end indices.
Answer:
t = tuple ( input ( " Enter ␣ tuple : ␣ " ) . split () )
start = int ( input ( " Start ␣ index : ␣ " ) )
end = int ( input ( " End ␣ index : ␣ " ) )

print ( " Slice : " , t [ start : end ])


8

Output:

Enter tuple: a b c d e
Start index: 1
End index: 4
Slice: (’b’, ’c’, ’d’)

17. Write a Python program to check whether an element exists


in a tuple.
Answer:
t = tuple ( input ( " Enter ␣ tuple : ␣ " ) . split () )
x = input ( " Enter ␣ element : ␣ " )

print ( " Exists " if x in t else " Does ␣ not ␣ exist " )

Output:

Enter tuple: a b c d
Enter element: c
Exists

18. Write a Python program to find the sum and average of nu-
meric elements in a tuple.
Answer:
t = tuple ( map ( float , input ( " Enter ␣ tuple : ␣ " ) . split () )
)

total = sum ( t )
avg = total / len ( t )

print ( " Sum ␣ = " , total )


print ( " Average ␣ = " , avg )

Output:

Enter tuple: 2 4 6 8
Sum = 20.0
Average = 5.0

19. Write a Python program to flatten a tuple of tuples.


Answer:
9

t = eval ( input ( " Enter ␣ tuple ␣ of ␣ tuples : ␣ " ) )

flat = []
for sub in t :
for x in sub :
flat . append ( x )

print ( tuple ( flat ) )

Output:

Enter tuple of tuples: ((1,2),(3,4),(5,6))


(1, 2, 3, 4, 5, 6)

20. Write a Python program to sort a tuple of integers.


Answer:
t = tuple ( map ( int , input ( " Enter ␣ tuple : ␣ " ) . split () ) )

sorted_tuple = tuple ( sorted ( t ) )


print ( sorted_tuple )

Output:

Enter tuple: 5 1 4 2 3
(1, 2, 3, 4, 5)
Python Programming Questions and Answers
(Part 2: Q21–Q40)

Questions and Answers


1. Write a Python program to read n integers into a list and find
the largest and smallest elements.
Answer:
n = int ( input ( " Enter ␣ n : ␣ " ) )
lst = []

for i in range ( n ) :
lst . append ( int ( input () ) )

largest = lst [0]


smallest = lst [0]

for x in lst :
if x > largest :
largest = x
if x < smallest :
smallest = x

print ( " Largest ␣ = " , largest )


print ( " Smallest ␣ = " , smallest )

Output:

Enter n: 5
10
3
25
7

1
2

15
Largest = 25
Smallest = 3

2. Write a Python program to compute the sum and average of


elements in a list.
Answer:
n = int ( input ( " Enter ␣ n : ␣ " ) )
lst = []

for i in range ( n ) :
lst . append ( float ( input () ) )

total = sum ( lst )


avg = total / n

print ( " Sum ␣ = " , total )


print ( " Average ␣ = " , avg )

Output:

Enter n: 4
2
4
6
8
Sum = 20.0
Average = 5.0

3. Write a Python program to remove duplicates from a list with-


out using set.
Answer:
n = int ( input ( " Enter ␣ n : ␣ " ) )
lst = []

for i in range ( n ) :
lst . append ( input () )

unique = []
for x in lst :
if x not in unique :
3

unique . append ( x )

print ( unique )

Output:

Enter n: 6
a
b
a
c
b
d
[’a’, ’b’, ’c’, ’d’]

4. Write a Python program to find the second largest element in


a list.
Answer:
n = int ( input ( " Enter ␣ n : ␣ " ) )
lst = []

for i in range ( n ) :
lst . append ( int ( input () ) )

largest = second = None

for x in lst :
if largest is None or x > largest :
second = largest
largest = x
elif x != largest and ( second is None or x >
second ) :
second = x

print ( " Second ␣ largest ␣ = " , second )

Output:

Enter n: 5
10
20
4

5
30
25
Second largest = 25

5. Write a Python program to separate even and odd numbers


from a list.
Answer:
n = int ( input ( " Enter ␣ n : ␣ " ) )
lst = []

for i in range ( n ) :
lst . append ( int ( input () ) )

evens = []
odds = []

for x in lst :
if x % 2 == 0:
evens . append ( x )
else :
odds . append ( x )

print ( " Evens : " , evens )


print ( " Odds : " , odds )

Output:

Enter n: 6
1
2
3
4
5
6
Evens: [2, 4, 6]
Odds: [1, 3, 5]

6. Write a Python program to count the frequency of each ele-


ment in a list.
Answer:
5

n = int ( input ( " Enter ␣ n : ␣ " ) )


lst = []

for i in range ( n ) :
lst . append ( input () )

freq = {}

for x in lst :
if x in freq :
freq [ x ] += 1
else :
freq [ x ] = 1

print ( freq )

Output:

Enter n: 5
a
b
a
c
b
{’a’: 2, ’b’: 2, ’c’: 1}

7. Write a Python program to rotate a list to the right by k


positions.
Answer:
n = int ( input ( " Enter ␣ n : ␣ " ) )
lst = []

for i in range ( n ) :
lst . append ( input () )

k = int ( input ( " Enter ␣ k : ␣ " ) )


k = k % n

rotated = lst [ - k :] + lst [: - k ]


print ( rotated )
6

Output:

Enter n: 5
1
2
3
4
5
Enter k: 2
[’4’, ’5’, ’1’, ’2’, ’3’]

8. Write a Python program to merge two sorted lists into one


sorted list without using sort().
Answer:
n1 = int ( input ( " Enter ␣ n1 : ␣ " ) )
a = []
for i in range ( n1 ) :
a . append ( int ( input () ) )

n2 = int ( input ( " Enter ␣ n2 : ␣ " ) )


b = []
for i in range ( n2 ) :
b . append ( int ( input () ) )

i = j = 0
merged = []

while i < n1 and j < n2 :


if a [ i ] <= b [ j ]:
merged . append ( a [ i ])
i += 1
else :
merged . append ( b [ j ])
j += 1

merged . extend ( a [ i :])


merged . extend ( b [ j :])

print ( merged )

Output:
7

Enter n1: 3
1
4
7
Enter n2: 4
2
3
6
8
[1, 2, 3, 4, 6, 7, 8]

9. Write a Python program to find the union and intersection of


two lists without using set.
Answer:
n1 = int ( input ( " Enter ␣ n1 : ␣ " ) )
a = []
for i in range ( n1 ) :
a . append ( input () )

n2 = int ( input ( " Enter ␣ n2 : ␣ " ) )


b = []
for i in range ( n2 ) :
b . append ( input () )

union = []
for x in a + b :
if x not in union :
union . append ( x )

intersection = []
for x in a :
if x in b and x not in intersection :
intersection . append ( x )

print ( " Union : " , union )


print ( " Intersection : " , intersection )

Output:

Enter n1: 4
a
8

b
c
d
Enter n2: 4
c
d
e
f
Union: [’a’, ’b’, ’c’, ’d’, ’e’, ’f’]
Intersection: [’c’, ’d’]

10. Write a Python program to remove all occurrences of a given


element from a list.
Answer:
n = int ( input ( " Enter ␣ n : ␣ " ) )
lst = []

for i in range ( n ) :
lst . append ( input () )

target = input ( " Enter ␣ element ␣ to ␣ remove : ␣ " )

result = []
for x in lst :
if x != target :
result . append ( x )

print ( result )

Output:

Enter n: 6
a
b
a
c
a
d
Enter element to remove: a
[’b’, ’c’, ’d’]
9

11. Write a Python program to sort a list of integers using bubble


sort.
Answer:
n = int ( input ( " Enter ␣ n : ␣ " ) )
lst = []

for i in range ( n ) :
lst . append ( int ( input () ) )

for i in range ( n ) :
for j in range (0 , n -i -1) :
if lst [ j ] > lst [ j +1]:
lst [ j ] , lst [ j +1] = lst [ j +1] , lst [ j ]

print ( " Sorted ␣ list : " , lst )

Output:

Enter n: 5
5
1
4
2
3
Sorted list: [1, 2, 3, 4, 5]

12. Write a Python program to sort a list using selection sort.


Answer:
n = int ( input ( " Enter ␣ n : ␣ " ) )
lst = []

for i in range ( n ) :
lst . append ( int ( input () ) )

for i in range ( n ) :
min_index = i
for j in range ( i +1 , n ) :
if lst [ j ] < lst [ min_index ]:
min_index = j
lst [ i ] , lst [ min_index ] = lst [ min_index ] , lst [ i ]
10

print ( " Sorted ␣ list : " , lst )

Output:

Enter n: 5
64
25
12
22
11
Sorted list: [11, 12, 22, 25, 64]

13. Write a Python program to perform linear search on a list.


Answer:
n = int ( input ( " Enter ␣ n : ␣ " ) )
lst = []

for i in range ( n ) :
lst . append ( int ( input () ) )

target = int ( input ( " Enter ␣ target : ␣ " ) )

found = False
for i in range ( n ) :
if lst [ i ] == target :
print ( " Found ␣ at ␣ index " , i )
found = True
break

if not found :
print ( " Not ␣ found " )

Output:

Enter n: 5
10
20
30
40
50
Enter target: 30
Found at index 2
11

14. Write a Python program to perform binary search on a sorted


list.
Answer:
lst = list ( map ( int , input ( " Enter ␣ sorted ␣ list : ␣ " ) .
split () ) )
target = int ( input ( " Enter ␣ target : ␣ " ) )

low , high = 0 , len ( lst ) -1


found = False

while low <= high :


mid = ( low + high ) // 2
if lst [ mid ] == target :
print ( " Found ␣ at ␣ index " , mid )
found = True
break
elif lst [ mid ] < target :
low = mid + 1
else :
high = mid - 1

if not found :
print ( " Not ␣ found " )

Output:

Enter sorted list: 1 3 5 7 9


Enter target: 7
Found at index 3

15. Write a Python program to find the maximum sum of a con-


tiguous subarray (Kadane’s algorithm).
Answer:
lst = list ( map ( int , input ( " Enter ␣ list : ␣ " ) . split () ) )

max_ending = max_so_far = lst [0]

for x in lst [1:]:


max_ending = max (x , max_ending + x )
max_so_far = max ( max_so_far , max_ending )

print ( " Maximum ␣ subarray ␣ sum ␣ = " , max_so_far )


12

Output:

Enter list: -2 1 -3 4 -1 2 1 -5 4
Maximum subarray sum = 6

16. Write a Python program to check whether two lists are equal
(same elements in same order).
Answer:
a = input ( " Enter ␣ list ␣ A : ␣ " ) . split ()
b = input ( " Enter ␣ list ␣ B : ␣ " ) . split ()

print ( " Equal " if a == b else " Not ␣ equal " )

Output:

Enter list A: 1 2 3
Enter list B: 1 2 3
Equal

17. Write a Python program to find all pairs of elements in a list


whose sum equals a target value.
Answer:
lst = list ( map ( int , input ( " Enter ␣ list : ␣ " ) . split () ) )
target = int ( input ( " Enter ␣ target : ␣ " ) )

for i in range ( len ( lst ) ) :


for j in range ( i +1 , len ( lst ) ) :
if lst [ i ] + lst [ j ] == target :
print ( lst [ i ] , lst [ j ])

Output:

Enter list: 1 2 3 4 5
Enter target: 6
1 5
2 4

18. Write a Python program to remove all negative numbers from


a list.
Answer:
13

lst = list ( map ( int , input ( " Enter ␣ list : ␣ " ) . split () ) )

result = [ x for x in lst if x >= 0]

print ( result )

Output:

Enter list: -5 3 -1 7 -2 9
[3, 7, 9]

19. Write a Python program to flatten a nested list (one level).


Answer:
nested = eval ( input ( " Enter ␣ nested ␣ list : ␣ " ) )

flat = []
for sub in nested :
for x in sub :
flat . append ( x )

print ( flat )

Output:

Enter nested list: [[1,2],[3,4],[5,6]]


[1, 2, 3, 4, 5, 6]

20. Write a Python program to split a list into two halves.


Answer:
lst = input ( " Enter ␣ list : ␣ " ) . split ()
mid = len ( lst ) // 2

first = lst [: mid ]


second = lst [ mid :]

print ( " First ␣ half : " , first )


print ( " Second ␣ half : " , second )

Output:
14

Enter list: a b c d e f
First half: [’a’, ’b’, ’c’]
Second half: [’d’, ’e’, ’f’]

You might also like