Lab - Questions and Solutions
Lab - Questions and Solutions
1. Raghav has been given the challenge to write a python program to add 5 and 7. How can he do so?
Code: print(5+7)
2.Vigyan was asked to print the following using the print function. Help him in writing a python program for the
same. (The Golden Ratio has the same letters as The God Relation.)
Code:print ("The Golden Ratio has the same letters as The God Relation.")
3.Indentation refers to the spaces at the beginning of a code line. Whereas in other programming languages the
indentation in code is for readability only, the indentation in Python is very important.
When the following code is run, it gives an IndentationError which is a compile-time error. Fix the code below and
produce the intended output
i=4
j=3
if (i>j):
print(i)
Code:i = 4
j=3
if (i > j):
print(i)
4.Mohit is a very naughty child, when his brother was away from his laptop, he changed his original program to the
following:
x = input()
y = input()
if x>y:
else:
This program does not throw an error when it is run, rather it throws an error during runtime. These kinds of errors
are known as runtime errors.
If we give x=1, and y=2, the program runs fine, but when we give x=2 and y=1, the program will throw an error.
Correct this code so that it is error-free.
Code:x = input()
y = input()
if x > y:
print("x is greater than y")
else:
print("y is greater than x")
5.Vishal was designing the front page of a website and he wrote the following code to display a message to the
user when he visits the website.
Correct Vishal’s code as the deadline is near and he is not able to solve the problem.
Code:
6.A friend told Dev that he can use the Python prompt to do some basic arithmetic operations without using the
input and output functions. Explain how he will perform the operation 50 + 40 -35 in python.
Code: print(50+40-35)
Code: num1 = 13
num2 = num1
print(id(num1)==id(num2))
num3 = 13
num4 = 12
print(id(num3)==id(num4))
CSET101-2023-Lab01-Tuesday
1.Smita does not know about the input and output functions in Python. How will she multiply 12 by 10 and display
the output?
Code:print(12*10)
2.Misha wants to create a script file in Python by the name of Misha.py which prints (My name is Misha.). Help her
to do so using the print() function with double quotes.
3.Your teacher has edited the correct program to test your knowledge. Now when you run the following code, it
gives a compile-time error. Fix this error and output the correct string.
4.Amaan and Ayaan were given x and y apples respectively and then they were asked to write a python program
that would input x and y and display how many apples each person had. You must write such a program.
Code:x = input()
y = input()
print("Amaan has",x,"apples.")
print("Ayaan has",y,"apples.")
5.Kushal is new to python programming and he was experimenting with the python multiple assignment features.
He wrote a program that would take in and assign 3 variables to 3 values in only 1 line of code. But while printing
the values, he made an error. Can you find and fix the error?
Code:a,b,c = 2,8,9
print (a,b,c)
c,b,a = a,b,c
print (a,b,c)
6.Kabir bought 20 mangoes and 23 oranges from a shop. Store these values in variables a and b in a program and
using print function display their respective values.
Code:a = 20
b = 23
print(a,b)
Code:a,b,c = 10,20,30
p,q,r = c-5,a+3,b-4
print ('a,b,c:', a,b,c, end ='')
print('p,q,r:',p,q,r)
CSET101-2023-Lab01-Wednesday
1.A friend told Dev that he can use the Python prompt to do some basic arithmetic operations without using the
input and output functions. Explain how he will perform the operation 50 + 40 -35 in python.
Code:print(50+40-35)
2. Karan runs a restaurant and he wants to calculate price of 1 steak and 1 ratatouille which cost x and y
respectively, input x and y from the user and display total cost customer has to pay.
Code:x = int(input())
y = int(input())
ans = x+y
print(ans)
3.As a software engineer in a good MNC, you must make students understand the importance of mathematics in
computer science (which is often overlooked). Do so by creating a fun program.
Write a python program to display the following string and store the file as Mathisfun.py.
Math is Fun so don't be resistant. Just learn the rules,the rules are consistent. And most important,you
must be persistent.
Code: print("Math is Fun so don't be resistant. Just learn the rules,the rules are consistent. And most important,you
must be persistent.")
4.Kshitij runs a car dealership and he wanted to display the cost of 4 cars which he had sold in the past week so
he wrote the code given in the editor.
Your task is to identify the problem with this code and fix it to print the prices of the cars (each in a new line)
code:x = input()
y = input()
a = input()
b = input()
print(x+"\n"+y+"\n"+a+"\n"+b)
code:age = 21
print ("You can vote")
7.Kabir bought 20 mangoes and 23 oranges from a shop. Store these values in variables a and b in a program and
using print function display their respective values.
Code:a = 20
b = 23
print(a,b)
CSET101-2023-Lab01-Thursday
Q1. You have been a software engineer for a decade and are used to writing programs in python2.x. So, to print
the string “Hello, World”, you wrote the following program:
Fix the code given above and print the string “Hello, World”.
Code
print ("Hello, World")
Q2. When writing a command line program for an assignment, Mr. Bruce Wayne wants to write a program that
prompts the user to input values for variables a and b, takes input, and then displays the data. Can you help him in
writing such a program?
Code
Q3. Vishal was designing the front page of a website and he wrote the following code to display a message to the
user when he visits the website.
Hi<name> ,
Correct Vishal’s code as the deadline is near and he is not able to solve the problem.
Code
Code
a = b = 0;
if(a == b):
c=a+b
print(c)
Q5. Find the errors in the following code
Code
Q6. Rishank bought 30 apples and 23 oranges from a shop. Store these values in variables a and b in a program
and using print function display their respective values.
Code
a = 30
b = 23
print(a,b)
Code
a,b,c = 10,20,30
p,q,r = c-5,a+3,b-4
print ('a,b,c:', a,b,c, end ='')
print('p,q,r:',p,q,r)
CSET101-2023-Lab01-Friday
Q1 . Nimish wrote the following code which gives a compile-time error. His teacher gave him a hint that this error
was caused because of some indentation problem. Your task is to find that problem and fix it to produce the
correct result.
Code
i=4
j=3
if (i>j):
print(i)
Q2 . Gautam wants to write a program in Python which asks for the values of d and e from the user and then
displays their values. Write a program to get input values for variables d and e from the user and display the data.
Code
d=input("Enter the value of d: ")
e=input("Enter the value of e: ")
print("Value of d: " +d)
print("Value of e: " +e)
Q3. Vedant writes a program to ask the number of boys and girls in the class from the user and then display their
values. What is the code Vedant would have written using the input and print functions.
Code
Q4. Rewrite the following code after removing all syntax errors:
Code
Code
a,b,c = 10,20,30
p,q,r = c-5,a+3,b-4
print ('a,b,c:', a,b,c, end ='')
print('p,q,r:',p,q,r)
Q7. Rivansh runs a restaurant and he wants to calculate price of 1 apple pie and 1 brownie which cost x and y
respectively, take input x and y from the user and display total cost customer has to paid.
Code
x = int(input())
y = int(input())
ans = x + y
print(ans)
CSET101-2023-Lab02-Monday
1. Two students want to determine which datatype the provided input belongs to. Create a program
that prints the class datatype that it belongs to.
Code:
a=int(input())
b=input()
print(type(a))
print(type(b))
2. Alice is imprisoned in Wonderland. To avoid this,she will write the values in the given string.
Create a program that converts the given string consists of variable values.
Code:
a,b=input().split()
b=int(b)
print("My name is {a}, I'm {b}.".format(a=a,b=b))
3. Sanyam cannot seem to figure out how to print decimal integers with two decimal places. Please
assist him in writing the software without utilizing the round function .
Code:
b=float(input())
print("%.2f"%b)
4.Sneha is trying to figure out how to make a single string out of three strings. Assist her in joining
all the strings together.
Code:
str1=input()
str2=input()
str3=input()
strf=str1+str2+str3
print(strf)
5. Rajat and Akash are having fun together. The game requires dividing game currency into two
teams and displaying the two teams scores along with their names on the gaming console.Help them
so that the game runs properly while printing it in single line.
Code:
a,x = input().split()
b,y = input().split()
x = int(x)
y = int(y)
print(a,"has a score of",x,"and ",end="")
print(b,"has a score of",y)
6. Ishita wishes to fill the string with the specified values without utilizing the string formatting
method. Help her fill in the values in accordance with the datatypes for each.
Code:
a=input()
b=int(input())
print("My name is %s, I have a bank balance of %d."%(a,b))
7. A Teacher asks her students to perform various operations on complex numbers. She gives them
the real and imaginary parts of 2 complex numbers and asks them to display the sum and difference
between them.
Code:
a = eval(input())
b = eval(input())
print("The sum is:", a+b)
print("The difference is:", a-b)
8. Ivary must select a partner for his hackathon, He is given ID number from -100 to 100. The
hackathon has a condition for partner selection that is the ID numbers should have opposite signs.
Ivary must make a programm to detect if two input ID have opposite signs using Bitwise operators.
Code:
x=int(input("Your ID: "))
y=int(input("Partner's ID: "))
if((x ^ y) < 0):
print ("Signs are opposite,you can be a team in the hackthon")
else:
print ("Signs are not opposite,you cant be a team in the hackathon")
9. Ishan and Hari are good friends, while Charu and William are good friends.Take the net income
of all four of them and verify the following:
CSET101-2023-Lab02-Tuesday
1. Kshitij wants to send his best pal a poem. He didn’t know how to create a program that will
display his message at the output terminal. Help him to write his code so that he can print the
message as shown in the sample output
Code:
print("Twinkle, twinkle, little star, \n\tHow I wonder what you are! \n\t\tUp above the world so
high, \n\t\tLike a diamond in the sky. \nTwinkle, twinkle, little star, \n\tHow I wonder what you
are!")
2. Teacher wants to know how to identify ascii value by entering a character.Create a program that
uses a function which prints the integer value of that input.
Code:
c=input()
print(ord(c))
3. Salma is new to python. She was writing a program that takes a value as input and prints double
of that value.
Can you find the mistake in her code and correct it?
Code:
a = input()
b = int(a)
c = 2*b
print("The double of",a,"is:", c)
4. Batman has been given a list of words from the riddler and he wants him to find out which of
those words are palindromes. If a word is a palindrome, he must display True and if not then False.
Can you help batman ?
Code:
a = input()
rev = a[::-1]
print(a==rev)
5. Chase was given a question which was basic python question where you add 1 to the input
number, but He want to impress His friends and teacher, So he tried using bit-wise operators. Add 1
to the input number using bit-wise operators.
Code:
n=int(input())
print((-(~n)))
6. Aman wants to tell his friend, Deepak an efficient way to do multiplication with 3.5. Write a
program to help Aman in finding an efficient way so that he can help his friend.
Code:
x=int(input())
print((x<<1) + x + (x>>1))
7. The grey kangaroo can jump 13.5 meters in one step. Take the input of the distance to be traveled
from the user and find out the number of steps (integer value) required for the grey kangaroo.
Code:
D=eval(input())
print(int(D/13.5))
8. If a five-digit even number is an input through the keyboard, write a program to calculate the sum
of its digits .
Code:
x=int(input())
x1=x%10
x2=(x//10)%10
x3=(x//100)%10
x4=(x//1000)%10
x5=(x//10000)%10
print(x1+x2+x3+x4+x5)
9. Rajesh has a long wire of length L. Out of this wire, he wants to create an n-sided polygon with
sides of equal length. Given n and L, find out the length of each side. Round off your answer to 2
decimal places.
Code:
L = float(input())
n = int(input())
ans = L/n
print("The size of each side will be:",round(ans, 2))
CSET101-2023-Lab02-Wednesday
1. Mohit is a software developer and his task is to convert a given amount of seconds into hours,
minutes, and seconds. Can you help him do this?
Code:
n = int(input())
h = n//3600
n = n % 3600
m = n//60
n = n%60
print("the time is ",h,":",m,":",n,sep="")
2. Rahul is writing a program to check the number of 1’s in the binary form a given number but he
fails to do so therefore he asked his friend to help him in writing a correct program so that he can
check the number of 1’s .
Code:
n=int(input())
print(bin(n).count('1'))
3. Vijaya takes input of any two numbers and then she writes code to perform Bitwise operators and
then prints output of 6 lines where (without using third variable):
1. First print bitwise AND operation
2. Second print bitwise OR operation
3. Third print bitwise NOT operation
4. Fourth print bitwise XOR operation
5. Fifth print bitwise right shift operation
6. Sixth print bitwise left shift operation
Code:
a=int(input())
b=int(input())
print("Bitwise AND operation",(a&b))
print("Bitwise OR operation",(a|b))
print("Bitwise NOT operation",(~b))
print("Bitwise XOR operation",(a^b))
print("Bitwise right shift operation",(a >> 2))
print("Bitwise left shift operation",(b << 2))
4. Nishant wants his younger sister, Ruhi to learn the python program for logical operators so he
asks her to perform the program by taking the input value in terms of true and false, and print the
results for and, or, and not operator. Write a python program to help Ruhi in writing the code.
Code:
a = input('Enter value of a:')
b = input('Enter value of b:')
print(a and b)
print(a or b)
print(not a)
5. A group of 7 teachers wants to go for some special python training session. The entire group is
only eligible if their research score on average is greater than 80 and they have a letter of invitation
from the organizers or permission letter from HOD. You are asked to get the percentage of 7
teachers. Now the task is to design a program that figures out the average percentage of all 7
teachers and check whether they can participate in the special python training session or not .
Three conditions:
3. Letter of invitation
Code:
a=eval(input())
b=eval(input())
c=eval(input())
d=eval(input())
e=eval(input())
f=eval(input())
g=eval(input())
score=(a+b+c+d+e+f+g)/7
Hod=str(input("HOD permission: "))
Invitation=str(input("Invitaion: "))
decision=str((Hod=='yes'or Invitation=='yes') and score>=80)
print("%s"%decision)
6. Amaan is playing KBC on his mobile phone. He wants to print the maximum winning amount
which he won in the game but there are many conflicts in the program that provides different
amount in the print statement. He needs your assistance to edit the code.
Code:
print("150 rupees")
#print("40 lakh")
print("7 Crore")
7. Ishita wishes to exchange Item No. X with another Item Y. Help her so that she can buy the
correct item.
Code:
x = input('Enter value of x: ')
y = input('Enter value of y: ')
temp = x
x=y
y = temp
print('The value of x after swapping: {}'.format(x))
print('The value of y after swapping: {}'.format(y))
8. Rajat and Akash are having fun together. The game requires dividing game currency into two
teams and displaying the two teams scores along with their names on the gaming console.Help them
so that the game runs properly while printing it in single line.
Code:
a,x = input().split()
b,y = input().split()
x = int(x)
y = int(y)
print(a,"has a score of",x,"and ",end="")
print(b,"has a score of",y)
9. Samarth wants to print all the noble gases of the periodic table with their atomic number. Create a
program that executes the above situation.
Code:
a=input()
b=int(input())
print(a,"with atomic number",b)
CSET101-2023-Lab02-Thursday
1. Three students want to determine which datatype the provided input belongs to. Create a program
that prints the class datatype that it belongs to.
Code:
a=int(input())
b=input()
c=float(input())
print(type(a))
print(type(b))
print(type(c))
2. A time machine was created by Himanshu. He wants to enter his name and the current date in the
machine terminal's time slot. Make a program that performs the scenario described above.
Code:
import datetime as dt
year, month, day =input().split()
year=int(year)
month=int(month)
day=int(day)
hour=int(input())
min=int(input())
sec=int(input())
n=input()
d = dt.datetime (year, month, day, hour, min, sec)
print("Timeslot: {d}, Name: {n}".format(d=d, n=n));
3. Antriksh has a very crappy PC. He must complete his python lab assignment on time. The given
assignment was to “Swap two numbers” but by following the steps he must make a temporary
variable but making a temp variable will occupy space, so he must make the program without using
a temporary variable. Write a program to help Antriksh in doing the task given to him
Code:
x = int(input())
y = int(input())
4.You are studying in the MIT and some of your friends want you to check if they can get admission
in MIT. But you got so many requests and at the same moment you have shortage of time, so you
decided to make a Python program to find the eligibility of admission for a professional course
based on the following criteria.
Eligibility Criteria :
Total in all three subjects >=190 or Total in Maths and Physics >=140
Code:
Math=int(input())
Phy=int(input())
Chem=int(input())
Totalallsubjects = Math+Phy+Chem
TotalinMathsPhysics = Math+Phy
if(Math>=65 and Phy >=55 and Chem>=50 and (Totalallsubjects >=190 or TotalinMathsPhysics
>=140)):
print("Eligible for admission")
else:
print("Not eligible for admission ")
5.Naveen wants to impress his little brother with extreme coding skills where Naveen decides to
show his brother magic trick. So Naveen writes a python code to check if the input character is
alphabet or no, if it’s an alphabet check whether if the character is Vowel or Consonant using
conditional operator .
Code:
input_char = input()
if ((int(ord(input_char)) >= 65 and int(ord(input_char)) <= 90) or (int(ord(input_char)) >= 97 and
int(ord(input_char)) <= 122)):
print("Input character is an alphabet.")
if(input_char in "aeiouAEIOU"):
print("Vowel")
else:
print("Consonant")
else:
print("Input character is not an alphabet.")
6. Write a program to surface area of a maximum size cone that can be inscribed in a cylinder of
height ‘h’ and radius ‘r’. Compute the result up to two decimal points.
Input Format:
First line contains an integer r that represents the radius of the cylinder
Second line contains an integer h that represents the height of the cylinder
Output format:
float value that represents the required calculated result up to two decimal points.
Code:
r = eval(input())
h = eval(input())
l = (r**2+h**2)**0.5
surface_area = (22*r*(r+l))/7
print('%.2f'%surface_area)
7. In a water tank, the tap leaks at a rate of one drop/second where 800 drops = 100 ml. Write a
program to find the liter count of water wasted in N days? N will be input in the test cases.
Code:
N=int(input())
#1sec=1drop
Seconds=N*24*60*60#secondsconversion
Wastage=Seconds*100/800
liters=Wastage/1000
print(int(liters))
8. Darshan takes input of any two numbers and then he writes code to perform arithmetic and
relational operator and then prints output of 13 lines where (without using third variable) :
#ExamplesofRelationalOperators
#a>bisFalse
print(a>b)
#a<b is True
print(a<b)
#a==b is False
print(a==b)
#a!=b is True
print(a!=b)
#a>=b is False
print(a>=b)
#a<=b is True
print(a<=b)
9. Suraj has sold 4 cars in the past week and wants to calculate his total sales and the average price
of a car. Can you help him?
Code:
a = int(input())
b = int(input())
c = int(input())
d = int(input())
sum = a+b+c+d
avg = (a+b+c+d)/4
print("The total sale is:", sum)
print("The average price of a car is:", avg)
9. Deepika wants to make her younger sister to learn an efficient way to reverse Bits of a Number.
Write a program to help Deepika so that she can make her younger sister learn the efficient way.
Code:
def reverseBits(n) :
rev = 0
# traversing bits of 'n' from the right
while (n > 0) :
# bitwise left shift 'rev' by 1
rev = rev << 1
# if current bit is '1'
if (n & 1 == 1) :
rev = rev ^ 1
# bitwise right shift 'n' by 1
n = n >> 1
# required number
return rev
n = int(input())
print(reverseBits(n))
CSET101-2023-Lab02-Friday
1. When Tanisha was a baby, she learned English words and then added those words together to
form sentences. Now that she is a CS student, she wants to write a program that does the same.
The input contains 6 lines, each containing 1 word.
Code:
a = input()
b = input()
c = input()
d = input()
e = input()
f = input()
ans = a+" "+b+" "+c+" "+d+" "+e+" "+f
print(ans)
2. Niharika has to design the welcome page of a website. To do this,she takes in 5 names as input
and displays them on the screen. Write a python program for doing the same task.
Code:
a = input()
b = input()
c = input()
d = input()
res = "Welcome, " + a + ", " + b + ", " + c + " and " + d + "!"
print(res)
3. You are given n number of balls and some number of boxes. Each box can contain maximum m
balls. Your task is to find the minimum number of boxes required to carry the given number of
balls.
4. Vidisha is a mathematician and she is asked that if she is given a complex number, she has to find
the 2 complex numbers whose lines on the plane are at right angles to the given number.
5. Given a 3-digit number, Hrithik wants to calculate the sum of the squares of all its digits taken
separately. Write a Python program to perform this computation.
Code:
a = input()
b = int(a[0])**2 + int(a[1])**2 + int(a[2])**2
print("The sum of the squares of each digit taken separately is:",b)
6. Vikram is new to python and he wants to work on complex numbers. The idea is to input real and
imaginary parts of 2 complex numbers and then output their product. Also, print the type
The input contains 4 lines, the first 2 have A and B for the first number and the last 2 have A and B
for the second number. The complex number is of the form A+Bj
Code:
a1 = int(input())
b1 = int(input())
a2 = int(input())
b2 = int(input())
n1 = complex(a1,b1)
n2 = complex(a2,b2)
ans = n1*n2
print("The product of the two complex numbers is:",ans)
print("The type of the product is:",type(ans))
7. You are given n number of lego blocks and you have to make some towers using them. Each
tower takes x blocks to make. You have to find the maximum number of towers that can be built
from the given blocks.
8. Write a program to implement the following problem. Ayush is working as an assistant professor
at the state university with X basic salary. Further, the university pays him house rent allowances
(HRA) of 12% of his basic salary and 40% of dearness allowances on his basic salary per month.
Furthermore, the university deducts 10% from his basic salary, and his dearness allowances towards
his contribution to the provident fund (PF) and the university deposits an equal contribution to his
PF account. Now, calculate his net salary per month and what is the total available amount in his PF
account after a year.
Code:
basic=int(input())
hra=basic*.12
da=basic*.40
pf=(basic+da)*.10
net_salary=basic+hra+da-pf
Total_pf_permonth=pf*2
print("Ayush's net salary:",net_salary)
print("Amount in the PF account after a year:", 12*Total_pf_permonth)
9. Deepika wants to make her younger sister to learn an efficient way to reverse Bits of a Number.
Write a program to help Deepika so that she can make her younger sister learn the efficient way.
Code:
def reverseBits(n) :
rev = 0
# traversing bits of 'n' from the right
while (n > 0) :
# bitwise left shift 'rev' by 1
rev = rev << 1
# if current bit is '1'
if (n & 1 == 1) :
rev = rev ^ 1
# bitwise right shift 'n' by 1
n = n >> 1
# required number
return rev
n = int(input())
print(reverseBits(n))
CSET101-2023-Lab03-Monday
1. There are two friends “A” and “B”. They find some apples in a forest. Given the number of
apples as input, type “yes” if they can be distributed among the two of them, else print “no”.
if(noOfApples % 2 == 0):
print("yes")
else:
print("no")
2.Given a parameter "X". Show the output as an area of a circle if the choice is the letter "c" or the
area of the square if the choice is "s". Round off to 2 decimal places.
code:
parameterX = int(input())
choice = input()
if choice == "c":
print(3.14*(parameterX**2))
elif choice == "s":
print(parameterX**2)
3.Write a program to take the sides of a triangle as input and determine whether it is an equilateral,
isosceles or scalene triangle
code:
side1 = int(input())
side2 = int(input())
side3 = int(input())
if side1==side2==side3:
print("Equilateral triangle")
elif side1==side2 or side2==side3 or side3==side1:
print("isosceles triangle")
else:
print("Scalene triangle")
4.Write a python program to determine the price of the gym membership with GST of 5% on the net
amount based on the following table
Month Charges(per
Range month)
1-2 2000/pm
3-9 1500/pm
10-12 1000/pm
>12 800/pm
if noOfMonth <=2:
amt = noOfMonth*2000+(noOfMonth*2000*0.05)
elif 3 <= noOfMonth <=9:
amt = noOfMonth * 1500 + (noOfMonth * 1500 * 0.05)
elif 10 <= noOfMonth <=12:
amt = noOfMonth * 1000 + (noOfMonth * 1000 * 0.05)
elif noOfMonth >12:
amt = noOfMonth * 800 + (noOfMonth * 800 * 0.05)
print(amt)
5. A man has purchased three eatable items like Pizza, Burger, and Pasta at the cost of Rs. X, Rs. Y,
Rs. Z. He has paid the bill. He wants to check the largest and the lowest cost mathematically.
Design a code to check the item with the largest price for him.
Code:
pizza = int(input())
burger = int(input())
pasta = int(input())
if pizza > burger and pizza > pasta:
print("Paid most for pizza:", pizza)
if burger < pasta:
print("Paid least for burger:", burger)
else:
print("Paid least for pasta:", pasta)
elif burger > pizza and burger > pasta:
print("Paid most for burger:", burger)
if pizza < pasta:
print("Paid least for pizza:", pizza)
else:
print("Paid least for pasta:", pasta)
elif pasta > pizza and pasta > burger:
print("Paid most for pasta:", pasta)
if pizza < burger:
print("Paid least for pizza:", pizza)
else:
print("Paid least for burger:", burger)
else:
print("All are equal")
6. Take 2 integers X and Y as input. Check if X is a multiple of Y without using loops. Output X/Y
value if it is a multiple, else output 0
code:
X = int(input())
Y = int(input())
if(X%Y == 0):
print(X/Y)
else:
print(0)
6. Take 2 integers X and Y as input. Check if X is a multiple of Y without using loops. Output X/Y
value if it is a multiple, else output 0
code:
X = int(input())
Y = int(input())
if(X%Y == 0):
print(X/Y)
else:
print(0)
y=0 (x=k),
y = ax^2 + bx + c (x<k)
Write a program to read all the values and return the final answer of y Order of inputs
(a,b,c,x,k)
code:
a = int(input())
b = int(input())
c = int(input())
k = int(input())
x = int(input())
fx = 0
if x > k:
fx = a*(x**2) - b*x + c
if x == k:
fx = 0
if x < k:
fx = (a*(x**2)) + b*x + c
print(fx)
Distanc
Charges
e
1-50 7 Rs./Km
51-100 350 + 10 Rs./Km
> 100 840 + 15 Rs/Km
Units
Charges
Consumed
0-100 0.50 per unit
101-200 Rs. 50 plus Rs. 1 per unit over 100 units
Rs. 150 plus 1.50 per unit over 200
201-300
units
Rs. 300 plus Rs.2 per unit over 300
> 300
units
Write a program to take the number of units consumed by the user and then calculate the electricity
bill.
10. An electronics store has the following rates for different types of laptop brands:
1. Acer – 25000
2. Hp – 35000
3. Dell – 45000
4. Asus – 60000
5. Apple – 80000
They are giving a 10% discount for online booking and 8% discount for advance booking and no
discount is given for on-spot booking.
1. First user input will be booking types like online, advance, or window booking.
2. Second user input will be brand.
Code:
b_type = input()
s_type = input()
if s_type=="Acer":
rate = 25000
elif s_type=="Hp":
rate = 35000
elif s_type=="Dell":
rate = 45000
elif s_type=="Asus":
rate = 60000
elif s_type=="Apple":
rate = 80000
else:
print("No such Brand")
if b_type=="online":
dis_per = "10%"
dis = rate * 0.1
print("Bill amount is", rate - dis)
elif b_type=="advanced":
dis_per = "8%"
dis = rate * 0.08
print("Bill amount is", rate - dis)
elif b_type=="window":
dis = 0
print("Bill amount is", rate - dis)
else:
print("Invalid Option")
CSET101-2023-Lab03-Tuesday
1. Sam’s dog Binary hears frequencies starting from 45 Hertz to 45000 Hertz (both inclusive). If
Sam’s commands have a frequency of XX Hertz, find whether Binary can hear them or not.
Code:
freq = int(input())
if 45 <= freq <= 45000:
print("YES")
else:
print("NO")
2. On a website that contains information about the artists, every user’s profile page is the list of
every event they have attended as a singer, dancer, or actor.
Given the number of events in each of these 3 categories(all three integers are distinct), find if the
user is a Singer, Dancer, or an Actor.
Code:
setter = int(input())
tester = int(input())
edito = int(input())
if setter > tester and setter > edito:
print("Singer")
elif tester > setter and tester > edito:
print("Dancer")
else:
print("Actor")
3. Write a python program to determine the price of the Club membership with GST of 5% on the
net amount based on the following table
code:
noOfMonth = int(input())
if noOfMonth <=2:
amt = noOfMonth*2000+(noOfMonth*2000*0.05)
elif 3 <= noOfMonth <=9:
amt = noOfMonth * 1500 + (noOfMonth * 1500 * 0.05)
elif 10 <= noOfMonth <=12:
amt = noOfMonth * 1000 + (noOfMonth * 1000 * 0.05)
elif noOfMonth >12:
amt = noOfMonth * 800 + (noOfMonth * 800 * 0.05)
print(amt)
4. A company is giving a retirement bonus of their retirement amount to all their employees retiring
this year. The retirement is based on the following table
Write a program to take the retirement amount as input and return the final amount (retirement
amount + bonus) as output.
Code:
retrAmt = int(input())
years = int(input())
if years < 5:
retrAmt = retrAmt + 0
elif years >=5 and years < 10:
retrAmt = retrAmt + (retrAmt*0.05)
elif years >=10 and years < 20:
retrAmt = retrAmt + (retrAmt*0.1)
elif years >=20:
retrAmt = retrAmt + (retrAmt*0.2)
print("Total Retirement Bonus:",retrAmt)
5. Take the height of the user (in meters) and the weight of the user (in kilograms) as the input and
calculate their BMI. Also, display which category they belong to based on the BMI.
code:
weight = int(input("weight in kg: "))
height = float(input("height in meters: "))
bmi = weight/(height**2)
print(round(bmi,2))
if 17 < bmi < 18.5:
print("Mild Thinness")
elif 18.8 <= bmi < 25:
print("Normal")
elif bmi > 25:
print("Overweight")
else:
print("inhumane stats")
code:
n = int(input().strip())
if n%2 != 0:
print("Weird")
elif (n%2 == 0 and 2<=n<=5):
print("Not Weird")
elif (n%2 == 0 and 6<=n<=20):
print("Weird")
elif (n%2 == 0 and n>=20):
print("Not Weird")
7. Take a character as input from the user and determine whether the input character is in
Uppercase, Lowercase, or is it a special character or a digit. (use ord())
code:
ch = input()
if ord(ch)>=65 and ord(ch)<=90:
print("Upper Case")
elif ord(ch)>=97 and ord(ch)<=122:
print("Lower Case")
elif ord(ch)>=48 and ord(ch)<=57:
print("Digit")
else:
print("Special Character")
8. Read 2 integers and a basic operator character(for eg: ‘+’ for addition) from the user as input to
perform all basic mathematical computations and print the result based on the user’s choice of the
operator.
+ for addition
- for addition
* for addition
/ for division
code:
n1 = int(input())
n2 = int(input())
ch = input()
ans = 0
if ch=='+':
ans = n1 + n2
print("The answer is:", ans)
elif ch == '-':
ans = n1 - n2
print("The answer is:", ans)
elif ch == '*':
ans = n1 * n2
print("The answer is:", ans)
elif ch == '/':
ans = n1 / n2
print("The answer is:", ans)
else:print("Invalid choice")
9. A commercial airline charges their customers for their excess baggage by its weight, type of
payment, and by type of flight. Check the following tables for domestic and international flights
respectively.
5kg Pre- 10kg Pre- 15kg Pre- 20kg Pre- 30kg Pre- At Airport Per
Currency
paid paid paid paid paid Kg
INR 2760 5520 8280 11040 16560 600
Write a python program to take the type of flight, type of payment and the weight of the baggage as
input and calculate the final amount to be paid by the user for their baggage.
Code:
flightType = input()
paymentType = input()
weight = int(input())
amt = 0
if flightType == "domestic":
if paymentType == "prepaid":
if 0 < weight <= 3:
amt = 1350
elif 3 < weight <= 5:
amt = 2250
elif 5 < weight <= 10:
amt = 4500
elif 10 < weight <= 15:
amt = 6750
elif 15 < weight <= 20:
amt = 9000
elif 20 < weight <= 30:
amt = 13500
elif paymentType == "at airport":
amt = weight*550
elif flightType == "international":
if paymentType == "prepaid":
if 0 < weight <= 5:
amt = 2760
elif 5 < weight <= 10:
amt = 5520
elif 10 < weight <= 15:
amt = 8280
elif 15 < weight <= 20:
amt = 11040
elif 20 < weight <= 30:
amt = 16560
elif paymentType == "at airport":
amt = weight * 600
print(amt)
10. A Bike dealership has the following rates for different types of bike brands:
a. TVS – 25000
b. Honda – 35000
d. KTM – 60000
e. Kawasaki – 80000
They are giving a 10% discount for online booking and an 8% discount for advance booking and no
discount is given for spot/window booking.
a. Ask the user to enter the booking type like online, advance, or window booking.
Code:
b_type = input()
s_type = input()
if s_type=="TVS":
rate = 25000
elif s_type=="Honda":
rate = 35000
elif s_type=="Royal Enfield":
rate = 45000
elif s_type=="KTM":
rate = 60000
elif s_type=="Kawasaki":
rate = 80000
else:
print("No such Brand")
rate = 0
if b_type=="online":
dis_per = "10%"
dis = rate * 0.1
print("Bill amount is", rate - dis)
elif b_type=="advanced":
dis_per = "8%"
dis = rate * 0.08
print("Bill amount is", rate - dis)
elif b_type=="window":
dis = 0
print("Bill amount is", rate - dis)
else:
print("Invalid Option")
CSET101-2023-Lab03-Wednesday
1. Take an integer as input from the user and determine whether the given number is
positive or negative
code:
n = int(input())
if n > 0:
print("positive")
else:
print("negative")
2. Given 3 sides, check whether these 3 sides form a triangle. (sum of 2 sides greater than the
remaining sides). Also for a triangle confirmation found, check if the triangle is isosceles.
Code:
a = int(input())
b = int(input())
c = int(input())
if (a+b>c and b+c>a and c+a>b):
print("This is a triangle")
if a==b or b==c or c==a:
print("And it's isosceles")
else:
print("Not isosceles")
else:
print("Not a triangle")
2. Given 3 sides, check whether these 3 sides form a triangle. (sum of 2 sides greater than
the remaining sides). Also for a triangle confirmation found, check if the triangle is
isosceles.
Code:
a = int(input())
b = int(input())
c = int(input())
if (a+b>c and b+c>a and c+a>b):
print("This is a triangle")
if a==b or b==c or c==a:
print("And it's isosceles")
else:
print("Not isosceles")
else:
print("Not a triangle")
3. A company is giving a retirement bonus of their retirement amount to all their employees retiring
this year. The retirement is based on the following table
Service < 5 years, bonus = 0
Service >= 5 years , bonus = 5%
Service >= 10 years, bonus = 10%
Service >= 20 years, bonus = 20%
Write a program to take the retirement amount as input and return the final amount (retirement
amount + bonus) as output.
Code:
retrAmt = int(input())
years = int(input())
if years < 5:
retrAmt = retrAmt + 0
elif years >=5 and years < 10:
retrAmt = retrAmt + (retrAmt*0.05)
elif years >=10 and years < 20:
retrAmt = retrAmt + (retrAmt*0.1)
elif years >=20:
retrAmt = retrAmt + (retrAmt*0.2)
print("Total Retirement Bonus:",retrAmt)
4. Write a python program to take the marks of the user as input and determine the grade based on
the table.
Code:
marks = int(input())
if marks >= 85:
grades = "A"
elif marks<=84 and marks>=60:
grades = "B"
elif marks<=59 and marks>=40:
grades = "C"
elif marks<=39 and marks>=30:
grades = "D"
else:
grades = "F"
print("grades:",grades)
5. Dia has borrowed Rs P from Ryan for T years and promised Ryan to pay the amount with the
interest. She must pay R% per year. Now she wants to calculate the total interest after five years.
Write a python code to calculates the total amount Dia must pay to Ryan depending upon whether
she must pay “simple” or “compound” Interest, absence of these cases must produce “Invalid
choice”.
Code:
principal = int(input())
rate = float(input())
time = int(input())
ch = input()
if ch == "simple":
A = principal*(1+((rate*time)/100))
print(A)
elif ch == "compound":
A = principal*((1+((rate/2)/100))**(2*time))
print(round(A,2))
else:
print("invalid choice.")
6. Take a character as input from the user and determine whether the input character is in
Uppercase, Lowercase, or is it a special character or a digit. (use ord())
code:
ch = input()
if ord(ch)>=65 and ord(ch)<=90:
print("Upper Case")
elif ord(ch)>=97 and ord(ch)<=122:
print("Lower Case")
elif ord(ch)>=48 and ord(ch)<=57:
print("Digit")
else:
print("Special Character")
6. Take a character as input from the user and determine whether the input character is in
Uppercase, Lowercase, or is it a special character or a digit. (use ord())
code:
ch = input()
if ord(ch)>=65 and ord(ch)<=90:
print("Upper Case")
elif ord(ch)>=97 and ord(ch)<=122:
print("Lower Case")
elif ord(ch)>=48 and ord(ch)<=57:
print("Digit")
else:
print("Special Character")
$y=ax^2-bx+c(x>k),$
$y=0 (x=k),$
$y=ax^2+bx+c(x<k)$
Write a program to read all the values and return the final answer of y order of inputs (a,b,c,x,k)
code:
a = int(input())
b = int(input())
c = int(input())
k = int(input())
x = int(input())
fx = 0
if x > k:
fx = a*(x**2) - b*x + c
if x == k:
fx = 0
if x < k:
fx = (a*(x**2)) + b*x + c
print(fx)
Distanc
Charges
e
1-50 7 Rs./Km
51-100 350 + 10 Rs./Km
> 100 840 + 15 Rs/Km
Write a program to take distance as input and calculate charges.
Code:
distance = int(input())
if 1 <= distance <= 50:
fare = distance * 7
print("The total fare is:",fare)
elif 51 <= distance <= 100:
fare = 350 + ((distance - 50) * 10)
print("The total fare is:",fare)
elif distance > 100:
fare = 840 + ((distance - 100) * 15)
print("The total fare is:",fare)
else:
print("Invalid fare")
9. A man wants to get the attractive last four digits of a registration number for his newly purchased
car. Though RTO has some VIP numbers, they are provided by adding some additional surcharge on
the cost of getting a normal registration number. The cost of getting a normal registration number is
5000 rupees whereas the additional surcharges for different VIP numbers are added according to the
pattern of the last four digits. The cost of these additional charges is given as follows.
Palindrome 3000
Divisible by 2 1000
Write a python program to compute the cost of a particular registration number if we feed the last four digits of that
number as input.
Code:
x=eval(input())
x1=x%10
x2=(x//10)%10
x3=(x//100)%10
x4=(x//1000)%10
rev_num = (10**3)*x1+(10**2)*x2+(10**1)*x3+(10**0)*x4
cost = 5000
10. A grade of a particular student for a specific course depends on her/his performance on the
following criteria’s.
1. Class Attendance marks (out of 10)
2. Midterm Exam marks (out of 20)
3. Class Assignment marks (out of 10)
4. Internal assessment marks of course instructor (out of 10)
5. End-term Exam Marks (out of 50)
So, based on her/his cumulative marks (out of 100), following rules are made by the instructor to assign an
absolute grade to a student.
Grade : Marks
A : >= 85
F : otherwise
Therefore, to assist the instructor, write a python program that takes marks of student on above five criteria’s and
accordingly assign a grade to her/him for that course.
Code:
cam = eval(input())
mte = eval(input())
cam1= eval(input())
iam = eval(input())
ete = eval(input())
total_marks = cam+mte+cam1+iam+ete
CSET101-2023-Lab03-Thursday
CSET101-2023-Lab03-Thursday
1.You are developing a program to calculate the sum of even numbers from 1 to 50, but you want to
stop the calculation if the sum exceeds 200. Implement a program that calculates and prints the sum
of even numbers, stopping if the sum goes beyond 200.
code:
n = int(input())
sum = 0
for num in range(1, n):
if num % 2 == 0:
if sum + num > 200:
break
sum += num
Code:
import random
while True:
guess = int(input("Guess a number between 1 and 100: "))
if guess == target_number:
print("Congratulations! You guessed the correct number.")
break
elif guess < target_number:
print("Too low! Try again.")
else:
print("Too high! Try again.")
3. Write a Python program to check if the given year is a leap year or not
code:
# if not divided by both 400 (century year) and 4 (not century year)
# year is not leap year
else:
print("{0} is not a leap year".format(year))
Code:
num = int(input("Enter a number: "))
original_num = num
reverse_num = 0
if original_num == reverse_num:
print(f"{original_num} is a palindrome number")
else:
print(f"{original_num} is not a palindrome number")
Code:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))
Code:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))
6. Two friends A and B are meeting after a long time. Usually, they love to play some math games.
This times A takes the call and decides the game. The game is very simple, A says out an integer
and B has to say whether the number is divisible by 4 or not. B as usual knows the logic but since A
does not give B much time to think, so B decides to write a python program. Task is to help B to
accomplish this task by writing a python program which will calculate whether the number is prime
or not.
Code:
x = eval(input())
x1=x%100
if x1%4 == 0:
print ('Yes')
else:
print('No')
7. A man is very curious, and usually wants to know whether the N squares of size 2x2 can be fit in
a right angled isosceles triangle of base B or not.
Note: One side of the square must be parallel to the base of the isosceles triangle. Base is the
shortest side of the triangle.
Code:
B=eval(input())
N=eval(input())
B = (B - 2)
B = B // 2
8. Rohit purchased the ball pens from three shops for the coming term end examination (TEE). He
purchased x pens from the first shop, y pens from the second shop and is yet to buy pens from the
third shop. Rohit is very superstitious and believes that if the sum of pens he buys from the three
shops is a divisible by 5, he'll clear the TEE. Please help him by calculating for him the minimum
number of pens that if purchased from the third shop will make the sum of pens as divisible 5.
Note: At least one pen should be bought from the third shop.
Code:
p_shop1 = eval(input())
p_shop2 = eval(input())
sum = p_shop1+p_shop2
rem = sum%5
if rem == 0:
p_shop3 = 5
elif rem == 1:
p_shop3 = 4
elif rem == 2:
p_shop3 = 3
elif rem == 3:
p_shop3 = 2
else:
p_shop3 = 1
print(p_shop3)
9. You are building an online shopping platform. Implement a program that calculates the final price
of a product based on its original price and a discount percentage. If the original price is above $\
$100$, provide an additional discount of 10%. If the final price after applying the discount is still
above $\$500$, offer an extra discount of 5%
Code:
original_price = float(input("Enter the original price: "))
discount_percentage = float(input("Enter the discount percentage: "))
final_price = original_price
10. You are a teacher assigning grades to students based on their exam scores. Implement a program
that takes a student's score as input and prints their corresponding grade. If the score is 90 or above,
the grade is 'A'. If the score is between 80 and 89, the grade is 'B'. If the score is between 70 and 79,
the grade is 'C'. If the score is below 70, the grade is 'F'.
code:
score = int(input("Enter the student's score: "))
CSET101-2023-Lab03-Friday
1. Write a program to calculate the price of a movie ticket based on the user's age and whether it's a
weekend or a weekday. The rules are:
For weekdays:
For weekends:
Children: $\$7$
Adults: $\$13$
Seniors: $\$10$
code:
age = int(input("Enter your age: "))
day = input("Enter day (weekend/weekday): ").lower()
if day == "weekend":
if age <= 12:
price = 7
elif age <= 60:
price = 13
else:
price = 10
else:
if age <= 12:
price = 5
elif age <= 60:
price = 10
else:
price = 7
Code:
if terms <= 0:
print("Enter a positive integer")
else:
for _ in range(terms):
fib_series.append(a)
a, b = b, a + b
Code:
num = int(input("Enter a number: "))
factors = []
Code:
n = int(input("Enter number: "))
rev = 0
while(n != 0):
rem = n % 10
rev = rev * 10 + rem
n = n // 10
print(rev)
Code:
n = int(input("Enter number: "))
rev = 0
while(n != 0):
rem = n % 10
rev = rev * 10 + rem
n = n // 10
print(rev)
Code:
start = int(input("Enter starting range: "))
end = int(input("Enter ending range: "))
if original_num == sum:
print(original_num, end=" ")
6. A person goes to the US Embassy to apply for a tourist visa. The embassy management grants a
visa if it fulfils the following three conditions:
Neg_RT_PCR = input()
Vaccine_status = input()
duration=eval(input())
if (Neg_RT_PCR == 'yes' or Vaccine_status == 'yes') and duration > 1 and duration <=15:
print('granted')
else:
print('denied')
7. The man had a box with N (2<=N<=5) balls of different weights and they are arranged inside it
according to their weights: A1, A2, ..., AN. (i.e., A1 <= A2 <= A3 <=…<= AN). He also had a one
ball whose weight is equivalent to number of balls that box contains, and it is placed in front of all
balls. This means that actually box contains N+1 balls. After a few minutes, in his excitement, he
started dancing with the box in his pocket, and the N+1 balls of that box got jumbled up. So now, he
no longer knows which of the N+1 balls have is weight equalling to N, and which the other balls
are. He wants to figure out the largest weight of the N balls. Write a python script that help him find
this.
Code:
l=list(input().split())
length = len(l)
if length == 2:
l = [int(l[0]), int(l[1])]
elif length == 3:
l = [int(l[0]), int(l[1]), int(l[2])]
elif length == 4:
l = [int(l[0]), int(l[1]), int(l[2]), int(l[3])]
else:
l = [int(l[0]), int(l[1]), int(l[2]), int(l[3]), int(l[4])]
l.remove(length-1)
print(max(l))
8. To reduce the pollution, the Delhi government has decided to apply the odd-even system by this
winter in the state. In this system, vehicles with odd numbers will be allowed to operate in MWFS
(Monday, Wednesday, Friday and Sunday) and vehicles with even numbers will be allowed in TTS
(Tuesday, Thursday and Saturday) in a week. Can you help the Delhi government to implement this
system in Python?
Code:
print("Enter your vehicle number (only last 4 digit integer number):")
Vehicle_No = int(input())
print("Enter the day of driving:")
Driving_day = str(input())
if((Vehicle_No%2 != 0) and ((Driving_day == "Monday") or (Driving_day == "Wednesday") or
(Driving_day == "Friday") or (Driving_day == "Sunday"))):
print("you are allowed to drive")
elif((Vehicle_No%2 == 0) and ((Driving_day == "Tuesday") or (Driving_day == "Thursday") or
(Driving_day == "Saturday"))):
print("you are allowed to drive")
else:
print("you are not allowed to drive, choose some other day.")
9. Write a program to calculate the rental price for a car based on the number of days and the car
type. The rules are:
Economy car: $\$40$/day
Compact car: $\$50$/day
SUV: $\$70$/day
Luxury car: $\$100$/day
Discount of 10% for rentals more than 7 days
code:
car_type = input("Enter car type (economy/compact/suv/luxury): ").lower()
rental_days = int(input("Enter number of rental days: "))
daily_rate = 0
if car_type == "economy":
daily_rate = 40
elif car_type == "compact":
daily_rate = 50
elif car_type == "suv":
daily_rate = 70
elif car_type == "luxury":
daily_rate = 100
10. Write a program for an ATM machine that dispenses cash. The ATM should consider the user's
account balance and whether the requested amount is a multiple of 10. The ATM should dispense
the requested amount if conditions are met.
Code:
account_balance = float(input("Enter your account balance: "))
withdraw_amount = int(input("Enter withdrawal amount: "))
if withdraw_amount % 10 != 0:
print("Withdrawal amount must be a multiple of 10")
elif withdraw_amount > account_balance:
print("Insufficient balance")
else:
account_balance -= withdraw_amount
print(f"Withdrawal successful! Remaining balance: ${account_balance:.2f}")
CSET101-2023-Lab04-Monday
1. A professor writes every number with a secret code on a board (where he is multiplying every digit of the
number) as given below in the sample patterns. He wants to automate the process using Python. Can you help
him?
Sample pattern:
235 = 30
150 = 0
151 = 5
Code:
2. Soham is playing a game of numbers where Soham is counting till an input number less than 98. Each time
when Soham encounter a multiple of five, he just passes (keep mum) instead of a number. Write a program for
implementing the same.
Sample Input:
12 #A number less than 100
Sample Output:
1
2
3
4
6
7
8
9
11
12
Sample Input:
101
Sample Output:
Invalid input
Code:
3. According to a game, person’s happiness is depend on the number of vowels in his/her name. Write a
program to count the number of vowels in the string.
Instruction:
Given a string, count the total number of vowels (a, e, i, o, u) in it. There are two methods to count total number of
vowels in a string.
Code:
# string object
str = input("insert a string ")
count = 0
for i in range(len(str)):
# Check for vowel
if str[i].upper() in ['A', 'E', 'I', 'O', 'U']:
count += 1
# Total number of Vowels
print("The number of vowel is: {}".format(count))
4. Write a program to take user defined input from user and calculate sum of digits using loop.
Code:
n = int(input())
sum = 0
while(n!=0):
sum += n%10
n = n//10
print(sum)
5. Jack answers the question ‘Yes’ only if the question is put up by himself else, he answers ‘No’. In a
questionnaire of 1 to 100, he has put his questions at numbers divisible by itself or one. Now, write a program to
take an input of question no. and check whether the Jack answers yes or no.
Code:
Number=int(input())
count=0
if Number>100:
print("invalid input")
else:
for i in range(2, (Number//2 + 1)):
if(Number % i == 0):
count+=1
break
pass
if count>=1 :
print("Jack says: No")
else : print("Jack says: Yes")
6. A shopkeeper needs to work on different mathematical binary operator (Addition, Subtraction, Multiplication and
Division) multiple times. He wants to automate the process using Python such a way so that he can apply the
above binary operator as many times he wishes to do it. Can you help him?
MENU
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Exit
Enter the choice:
Code:
elif choice == 2:
print( "SUBTRACTION")
a = int( input("First Number: "))
b = int( input("Second Number: "))
print("{} - {} = {}".format(a, b, a - b) )
elif choice == 3:
print( "MULTIPLICATION")
a = int( input("First Number: "))
b = int( input("Second Number: "))
print("{} * {} = {}".format(a, b, a * b) )
elif choice == 4:
print( "DIVISION")
a = int( input("First Number: "))
b = int( input("Second Number: "))
print("{} / {} = {}".format(a, b, a / b) )
elif choice == 5:
print("Exit from loop")
break
else:
print( "Please Provide a valid Input!")
7. In an IAS class of n students, take input of age of all the students one at a time and display the average age of
the students. You are not given the whole input at a time, and the data comes in the streaming process.
Code:
i=1
sum=0
num=int(input("Enter how many students?"))
print("enter age:")
while i<=num:
n=eval(input())
sum+=n
i+=1
print("The average age is:", sum/num)
8. Consider the different alphabetic symbols and take a number as input which is nothing but number of rows to
be printed as the following pattern given.
Code:
1. Pranav is playing a game of numbers where Pranav is counting till an input number less than 200. Each time
when Rohan encounter a multiple of four, Pranav say “great” instead of a number. Write a program in python for
Pranav.
Code:
Num=int(input())
i=1
while i <= Num :
if i%4 !=0 :
print(i)
else :
print('great')
i+=1
2. Richa is earning 23rs per month. Her salary gets double in second month and triple in third month and so on.
Write a python program to print her salary for coming n months individually using while loop.
Code:
no=int(input())
i=2
while i <=no+1 :
print(23*i)
i+=1
3. Lalit wants to print all the characters in a given input string until a first small case character is encountered.
Write a program to help Lalit. Hint: Take input of any string and print all characters until the break condition as
specified.
Code:
str=input()
for i in str:
j=ord(i)
if j>=97 and j<=122 :
break
print(i)
4. Humpty Sharma believes in the relationship between numbers. He decides to go ahead for his Dulhania with
the permission of parents. He will call parents from number who’s sum of digits is greater than 60 by calculating
the sum of the digits. Write a python program to implement the logic.
Code:
5. Rovin just hates the character 'y'. He copies all in his speech character by character until the hate character 'y'
is encountered. Design a program to output all the characters in the string until 'y' is encountered.
Code:
str=input()
for i in str:
if i=='y'or i=='Y' :
break
print(i)
6. Shikha is in python lab. She stuck in between to calculate first two factors (other than 1) of a given positive
integer. Write a program to calculate first two factors of given number and let her know in case number is not
having any factor.
Code:
n=int(input())
count=0
i=2
while count< 2 and i<=n/2:
if n%i==0:
print(i)
count+=1
i+=1
if count<2 : print("Number is prime")
7. Taran is a very intelligent guy. He is a master of numbers. He can remember any numbers. Once in a talent
hunt shows he was asked to demonstrate the count of positive numbers, negative numbers, and zeros which were
input by the host. Write a program for Taran to enter the numbers he desired and in the end, it should display the
count of positive, negative and zeros entered to verify whether Taran is right or wrong.
Code:
8. Soham wants to find the value of the following expression for the given values of X and N. Write a python
program to help Soham.
Note that you must use single for-loop (no nesting loops are allowed)
1 + X + X^2 / 2! + X^3/3! + ... + X^N/N!
Code:
x=float(input("Enter x = "))
n=int(input("Enter n = "))
fact=1
X=1
value=1
CSET101-2023-Lab04-Wednesday
1. Jorge is assigned a task to take string input from user and print its individual letters except vowels using while
loop in python.
Code:
word = input()
i=0
while i < len(word):
if word[i] == "a" or word[i] =="e" or word[i] =="i" or word[i] =="o" or word[i] =="u":
i += 1
continue
print(word[i], end="")
i += 1
2. Navya is writting a program to take input number of rows and print the following patterns using nested for loop.
Code:
3. The central importance of prime numbers to number theory and mathematics in general stems from the
fundamental theorem of arithmetic. This theorem states that every integer larger than 1 can be written as a product
of one or more primes. Write a python program to list out the prime numbers between two given number.
Code:
lower = int(input())
upper = int(input())
l = []
For Example: 145 is strong number. Since, 1! + 4! + 5! = 145. Write a python program to print all strong number
series between the range entered by the user.
Code:
s=int(input("Enter Start:"))
e=int(input("Enter End:"))
for num in range(s,e):
sum1=0
temp=num
while(num):
i=1
f=1
r=num%10
while(i<=r):
f=f*i
i=i+1
sum1=sum1+f
num=num//10
if(sum1==temp):
print(sum1)
5. If the sum of nth power (where n is the number of digits in the input number) of each digit is equal to the original
number then the number is known as Armstrong number. For example if the number is 153 then its Armstrong
number will be (1*1*1)+(5*5*5)+(3*3*3) = 153
Code:
n = int(input())
s=n
b = len(str(n))
sum1 = 0
while n != 0:
r = n % 10
sum1 = sum1+(r**b)
n = n//10
if s == sum1:
print("The given number", s, "is armstrong number")
else:
print("The given number", s, "is not armstrong number")
6. Rishabh has got a python assignment in the lab to print the sum of all prime numbers up to N where N is
entered by user.
Code:
i=2
flag = 0
while i<num:
if num % i == 0:
flag = 1
#print (num,"is NOT a prime number.");
break
i = i + 1 #Updating the value of i on every iteration by 1
if flag == 0:
sum+=num
7. Write python program to take input number of rows from the user and print the following pattern.
Code:
8. A number is said to be a magic number, if the sum of its digits are calculated till a single digit recursively by
adding the sum of the digits after every addition. If the single digit comes out to be 1,then the number is a magic
number.
For example-
Number= 50113
=> 5+0+1+1+3=10
=> 1+0=1
This is a Magic Number
Code:
n = int(input())
sum = 0;
while (n > 0 or sum > 9):
if (n == 0):
n = sum;
sum = 0;
sum = sum + n % 10;
n = int(n / 10);
if (sum == 1):
print("Magic Number");
else:
print("Not a magic Number");
CSET101-2023-Lab04-Thursday
1. Ramesh told two numbers to his child and asked to find only those divisors that are divisible by 1 or themselves.
Can you help his child in solving the problem?
Code:
2. Raghaw wants take input number of rows and print the following alphabet pattern. Help him to write the
program.
Example:
A
BC
DEF
GHIJ
KLMNO
PQRS
TUV
WX
Y
Code:
3. Suppose your mom is asking to generate and print a series of numbers up to a given number (i.e., number of
terms is the input given by her) such that each number in the series is equal to the sum of its previous two
numbers. Do this problem using Python.
Example:
0 1 1 2 3 5 8 13……
Code:
4. Amicable numbers are two different natural numbers related in such a way that the sum of the proper divisors
of each is equal to the other number. For example, σ(a)=b and σ(b)=a, where σ(n) is equal to the sum of positive
divisors of n. Write a Python Program to check if two numbers are amicable numbers or not.
Example:
220 and 284 are examples of amicable numbers. The factors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55, and 110, which sum to
284, while the factors of 284 are 1, 2, 4, 71, and 142, which sum to 220.
Code:
5. Write a program that enters two integers n and l and generates in alphabetical order all possible "dumb”
passwords", that consist of the following 5 characters:
n = int(input("Enter n: "))
I =int(input("Enter I: "))
result = ''
for s1 in range(1, n + 1):
for s2 in range(1, n + 1):
for s3 in range(97, I + 97):
for s4 in range(97, I + 97):
for s5 in range(max(s1,s2) + 1, n + 1):
result += ('' + str(s1) + str(s2) + chr(s3) + chr(s4) + str(s5) + ' ')
print (result.strip())
6. Perfect number is a positive number which sum of all positive divisors excluding that number is equal to that
number. For example, 6 is perfect number since divisor of 6 are 1, 2 and 3. Sum of its divisor is 1 + 2+ 3 = 6
Write a python program to print perfect number series up to N, where N is entered by user.
Code:
7. A professor writes a question on a white-board in his class. The question is to find those positive integer
numbers between a given ranges (inputs to the program) such that the nth order sum of digits of a number (with n
digits) is the number itself. Can you help the class to automate this process in Python?
Example:
153 = 13+53+33
1634 = 14+64+34+44
Code:
8. You have a task to write a program to help an astrologer in numerology. Given the date of birth of a person in
the form of dd-mm-yyyy format, your program should able to find out his lucky number. The lucky number of a
person is calculated by adding the digits of the date of birth. The digits are added until it is between a number
between 0 and 9. Example: 05-08-1986, the initial summation of digits are equal to 37, the digits are again added
and it becomes 10 and once again the digits are added which become 1, finally.
Code:
s=input()
dob=int(s[:2]+s[3:5]+s[6:])
n=dob
s=0
while n>=10:
s=n
s1=0
while s>0:
s1=s1+s%10
s=s//10
n=s1
print('Numerology number is:',n)
CSET101-2023-Lab04-Friday
1. Aniket works in MNC. His project manager asked him to write a program to count the occurrence of
different digits in the entered pin and reject the pin if it contains any digits more than once.
Code:
pin = input()
zero=0; one=0; two=0; three=0; four=0; five=0; six=0; seven=0; eight=0; nine=0;
for i in pin:
if i == "0":
zero += 1
elif i == "1":
one += 1
elif i == "2":
two +=1
elif i == "3":
three += 1
elif i == "4":
four += 1
elif i == "5":
five += 1
elif i == "6":
six += 1
elif i == "7":
seven += 1
elif i == "8":
eight += 1
elif i == "9":
nine += 1
if zero >=2 or one >=2 or two >=2 or three >=2 or four >=2 or five >=2 or six >=2 or seven >=2 or eight >=2
or nine >=2:
print("Reject Pin")
else:
print("Accept Pin")
2. Given N1 and N2 as two numbers, write a program that will display all the numbers including N1 and N2 which
have all odd digits.
Code:
N1=int(input())
N2=int(input())
for i in range(N1,N2+1):
s=str(i)
f=True
for j in s:
if (int(j))%2==0:
f=False
break
if f:
print(i,end=' ')
3. A fractional number is represented as N/M where both N and M are integers. Given the values of Numerator
and Denominators as positive integers, simplify the fraction in n/m form so that n and m are co-primes. Any two
numbers are co-prime numbers if, the maximum common factor between them is 1.
Code:
N=int(input())
M=int(input())
a=N
b=M
if b>a: a,b=b,a
GCD=1
if b==0:
GCD=a
else:
c=a%b
a=b
b=c
while b>0:
c=a%b
a=b
b=c
GCD=a
n=N//GCD
m=M//GCD
#print(GCD)
print('{}/{} is simplified as {}/{}'.format(N,M,n,m))
4. Rishita is participating in a competition where she is assigned a task print the following pattern.
Code:
rows = 5
print("Enter the first symbol for the pattern:")
pattern1 = input()
print("Enter the second symbol for the pattern:")
pattern2 = input()
for i in range(0, rows):
for j in range(0, i + 1):
print(pattern1, end=pattern2)
print("\r")
5. Armstrong number is thought of as number if the sum of its own digits raised to the power number of digits
gives the number itself.
Write a python program to check given number is Armstrong number or not.
Example:
153 = 13+53+33
1634 = 14+64+34+44
Code:
num=int(input("Enter number:"))
l=len(str(num))
sum = 0
temp = num
# find the sum of the cube of each digit
while temp > 0:
digit = temp % 10
sum += digit ** l
temp //= 10
if num == sum:
print(num, "is Armstrong number.")
else:
print(num, "is not Armstrong number.")
6. Jack answers the question ‘Yes’ only if the question is put up by himself else, he answers ‘No’. In a
questionnaire of 1 to 100, he has put his questions at numbers divisible by itself or one. Now, write a program to
take an input of question no. and check whether the Jack answers yes or no.
Code:
Number=int(input())
count=0
if Number>100:
print("invalid input")
else:
for i in range(2, (Number//2 + 1)):
if(Number % i == 0):
count+=1
break
pass
if count>=1 :
print("Jack says: No")
else : print("Jack says: Yes")
7. Write python program to take input number of rows from the user and print the following pattern.
Code:
8. The number 99 has a special identity that if we multiply its digits together and then add the sum of its digits to
that, we get back to 99. That is, (9 * 9) + (9 + 9) = 99. Write a program to find all of the numbers less than given N
as input with this property.
Code:
CSET101-2023-Lab05-Monday
1. Create a list by taking input from the user. First input is the no. of elements you want to add in the list and
second input is the elements. Create a new list which is reverse of the existing list.
First output should be existing list and second output should be resultant list.
Code:
n=int(input())
list1=[]
for i in range(n):
list1.append(int(input()))
list2 = list1[::-1]
print( list1)
print( list2)
2. Create a list which consists of only integer values by taking input from the user. Take first input as the number of
elements you want to add in the list and second input as the elements in the list. Write a program to create a new
list where each element value is the square of elements of the existing list.
Code:
n = int(input())
list1 = []
for i in range(n):
list1.append(int(input()))
list2 = [i**2 for i in list1]
print(list2)
3. Create a list by taking input from the user. Take the first input as the number of elements to be added in the list,
second input as the elements in the list and the third input as an element to be searched in the list. Search the first
occurrence of an element named elem in the list. When found print the index position where it is found and replace
elem with the result of the addition of the value 1000. If the element is not found in the list then print the message
"The element you are searching for is not in the list”.
Code:
n = int(input())
list1 = []
for i in range(n):
list1.append(int(input()))
elem = int(input())
if elem in list1:
index = list1.index(elem)
list1[index] = elem + 1000
else:
print("The element you are searching for is not in the list")
4. Create two same size lists by taking inputs from the user. Take first input as the size of the lists and second and
third inputs be the contents of both the lists. Each list should only contain string as its member elements. Create a
resultant list such that this list contains the index- wise concatenation result of elements of first list with second
list.
Code:
size = int (input ())
for i in range(size):
list1.append(input ())
for i in range(size):
list2.append(input ())
if all(isinstance(item, str) for item in list1) and all(isinstance(item, str) for item in list2):
resultant_list = [list1[i] + list2[i] for i in range(size)]
print("Resultant List:", resultant_list)
5. Create two same size lists by taking inputs from the user. Take first input as the number of elements to
add in the lists, second input as the elements in the first list , the third input as the elements in the
second list and fourth input as the elements of the second list. Each list should only contain string as its
member elements. Iterate over both the lists simultaneously and display the elements of first list in the
same order and the second list in the reverse order.
Code:
l=int(input())
list1=[]
for i in range(l):
list1.append(input())
list2=[]
for i in range(l):
list2.append(input())
for x,y in zip(list1,list2[::-1]):
print(x,y)
6. Create a list by entering the items separated by space. (only integer values). Write a program to find if
the contents are palindrome. If while reading the element values in the list, it is found that front to end
and end to front, the elements are read as same, then print: Yes, otherwise print not palindrome.
Code:
a=list(input().split(' '))
i=0
mid=len(a)/2
same=True
while i<mid:
if a[i]!=a[len(a)-i-1]:
print("Not palindrome")
same=False
break
i+=1
if same==True:
print("Yes")
7. Create a list by taking input from the user and which consists of only integer values.. First input is the
size of the list and second input is the elements in the list. Print the product of the list as output.
Code:
n = int(input())
test_list = []
for i in range(n):
test_list.append(int(input()))
prod_numbers=1
for x in test_list:
prod_numbers *= x
print(prod_numbers)
8. Create a list of n elements by taking input from the user and which consists of only strings as its
element. The user may enter empty strings. Write a program to remove empty strings from the user.
Code:
test_list = input().split(",")
result_list = list(filter(lambda x: x.strip(), test_list))
print("Resultant list:", result_list)
CSET101-2023-Lab05-Tuesday
1. You have given a list of students of a batch. You have to check whether the student is part
of the batch or not. Write a Python program to check whether a student is in a batch or not.
Format Input:
Student list: ram shyam
Name of student: ram
Code:
lst = input().split()
r = input()
if r in lst:
print("Student is part of batch")
else:
print("Student is not part of batch")
2. In an attendance sheet, names of students are listed. Again, a duplicate attendance sheet
is created. The entries in duplicate attendance sheet is lesser than the original attendance
sheet. We must find the missing name in the duplicate attendance sheet to avoid any
ambiguity. Write a python program to solve the mentioned problem.
Code:
def lostElement(A,B):
A = set(A)
B = set(B)
if len(A) > len(B):
print ("{}".format(list(A-B)))
else:
print ("{}".format(list(B-A)))
A = set(input().split())
B = set(input().split())
lostElement(A,B)
3. Create a list named ‘list1’ by taking input from the user. The list consists of only integer
values. A mapping function F(x)=x3+2x-5 is applied on list1, and the output is saved in list2.
Create list2 where the mapped value is saved. Display list1 and list2.
Code:
def F(x):
return x**3 + 2*x - 5
# Apply the mapping function to each element of list1 and save to list2
list2 = [F(x) for x in list1]
4. Alice and Bob are meeting after a long time. As usual they love to play some math games.
This times Alice takes the call and decides the game. The game is very simple, Alice says out
an integer and Bob has to say whether the number is prime or not. Help Bob accomplish this
task by writing a python program which will calculate whether the number is prime or not.
Code:
n = int(input())
li = []
for i in range(n):
li.append(int(input()))
for j in li:
count = 0
for i in range(1,j+1):
if((j % i) == 0):
count = count + 1
if(count == 2):
print("yes")
else:
print("no")
5. A company is providing discount of 50% on any one item (the item with least MRP) purchased by the
customer if total bill amount is above 1500/-. Take the number of items purchased and MRP of each item
as an input and print the final bill including discount.
Code:
l = int(input())
total=0
lst = []
for i in range(l):
lst.append(float(input()))
minimum = min(lst)
for i in range(0, len(lst)):
total = total + lst[i]
print("The total price is Rs {}".format(total))
if total>1500:
Dp = total-(minimum/2)
print("The discount is Rs {}".format(minimum/2))
else:
print("The discount is Rs 0")
Dp = total
print("The discounted price is Rs {}".format(Dp))
6. We want to group together students of two different batches (entered in two different lists). But the
problem is that we don’t want synchronized combination. The first student of batch1 should be mapped
with the last student of batch 2, and second student of batch 1 should be mapped with second last
student of batch 2 and so on. Write a python code for doing such mapping using list.
Code:
l = int(input())
list1 = [ ]
for i in range(l):
list1.append(input())
list2 = [ ]
for i in range(l):
list2.append(input())
for x, y in zip(list1, list2[::-1]):
print("{} is mapped with {}".format(x,y))
7. You are given three integers x, y and z representing the dimensions of a cuboid along with an integer n.
Print a list of all possible coordinates given by (i, j, k) on a 3D grid where i+j+k the sum of is not equal to
n. Here, 0<=i<=x, 0<=j<=y, 0<=k<=z. Print the list in lexicographic increasing order.
Example
x=1
y=1
z=2
n=3
Code:
x = int(input())
y = int(input())
z = int(input())
n = int(input())
listijk = []
for i in range(x + 1):
for j in range (y + 1):
for k in range (z + 1):
if i + j + k != n: #before printing the result, it will exclude the output which 'i' + 'j'
+ 'k' is the same as 'n'.
listijk.append([i,j,k])
print(listijk)
8. Write a python program to enter list of 10 numbers. Write a program to create two lists "asc" and "des" where
the numbers in "asc" are arranged in ascending order and "des" are ordered in descending order.
Input format:
List of numbers
Order (asc/des)
Code:
Numbers=[]
for i in range(10):
no=int(input())
Numbers.append(no)
order = input()
if order == 'asc':
Numbers.sort()
elif order == 'des':
Numbers.sort(reverse=True)
print(Numbers)
CSET101-2023-Lab05-Wednesday
1. Create a list named ‘list1’ by taking input from the user. The list consists of only integer values. A mapping
function F(x) = x2+5x+5 is applied on list1, and the output is saved in list2. Create list2 where the mapped value is
saved. Display list1 and list2. [Use for loop}
Code:
print("Enter the number of elements you want to add in the list")
n = int(input())
list1 = []
print("Enter element value in the list")
for i in range(n):
list1.append(int(input()))
list2 = []
for i in list1:
y = i**2+5*i+5
list2.append(y)
print("The entered value in list1 is:",list1)
print("The mapped value in list2 is:",list2)
2. You are given a list of integer values(to be taken by user) a1, a2, ..., aN. Find the smallest possible value of ai +
aj, where 1 ≤ i < j ≤ N. [Use list]
Input Format:
N integers: a1, a2, .. aN
Sample Input:
5134
Output:
Explanation:
3. In a university batch of students is decided on the basis of students’ marks. There are two lists of batches of
students. Write a python program to move students from the list of one batch to another.
Input Format:
Student to move
Input:
Output:
Code:
print("List of students from batch1: ")
b1 = input().split()
print("List of students from batch2: ")
b2 = input().split()
print("Student to move: ")
s_name = input()
ind = b1.index(s_name)
name=b1.pop(ind)
b2.append(name)
print("Updated Batch 1=",b1)
print("Updated Batch 2=",b2)
4. Write a python program to create a list with input from the user of non-repetitive numbers A and find five lists,
one contains all prime numbers in A, second one contains composite numbers in A, the third list contains all
numbers in A which are neither divisible by 2, fourth and fifth list contains number divisible by 3 and 5 respectively.
Input Format:
1. Number of elements
2. List of elements
Output Explanation:
List of
1. Prime numbers
2. Composite numbers
3. Divisible by 2
4. Divisible by 3
5. Divisible by 5
Code:
a=int(input())
Aa = []
for i in range(a):
no=int(input())
if no not in Aa:
Aa.append(no)
else: continue
A=[]
B=[]
C=[]
D=[]
E=[]
#print("Prime numbers from the list are as follows:")
for a in Aa:
count=0
for i in range(1,a+1):
if (a%i==0):
count=count+1
if count==2:
A.append(a)
if count>2:
B.append(a)
if (a%2==0):
C.append(a)
if (a%3==0):
D.append(a)
if (a%5==0):
E.append(a)
print(A)
print(B)
print(C)
print(D)
print(E)
5. You have given a list of integers with duplicate elements in it. The task to generate another list, which contains
only the duplicate elements. In simple words, the new list should contain the elements which appear more than
one. Write a python program that take user defined inputs and give output of duplicate elements.
Code:
n = int(input("Enter no.of list elements: "))
lst = []
for i in range(n):
lst.append(int(input()))
repeated = []
for i in range(n):
k=i+1
for j in range(k, n):
if lst[i] == lst[j] and lst[i] not in repeated:
repeated.append(lst[i])
print("duplicate elements list: ",repeated)
6. A grocer has a sale of Rs. A1, Rs. A2, Rs. A3, Rs. A4 and Rs. A5 for 5 consecutive months. How much sale
must he have in the sixth month so that he gets an average sale of Rs. Average? Write a python program to
calculate required sale in sixth month.
Input Format:
List of sale = A1 A2 A3 A4 A5
Example:
Average = 6500
Total sale for 5 months = Rs. (6435 + 6927 + 6855 + 7230 + 6562) = Rs. 34009.
= Rs. 4991
Code:
lst = [int(x) for x in input().split()]
avg = int(input())
sum = 0
rs = 0
for i in lst:
sum = sum + i
rs = 6*avg - sum
print("Required Sale Amount:",rs)
7. Write a program that accepts two positive integers a and b (a is smaller than b) and returns a list that contains
all the odd numbers between a and b (including a and including b if applicable) in reverse order without using
reverse function.
Code:
a=int(input())
b=int(input())
output_list=[]
for number in range(a,b+1):
if number%2==1:
output_list.append(number)
count=len(output_list)-1
for i in range(0,len(output_list)//2):
temp=output_list[i]
output_list[i]=output_list[count-i]
output_list[count-i]=temp
print(output_list)
8. A car owner buys petrol at Rs. R1, R2, and R3 per litre for three successive years. What approximately is the
average cost per litre of petrol if he spends Rs. R each year? .
Write a python program to for such situation. Take cost of petrol for successive years in a list.
Input format:
List = R1 R2 R3
Spend amount = R
Explanation:
consumed in 3 years
= 76700/51
Code:
lst = [eval(x) for x in input().split()]
r = int(input())
sum = 0
rs = 0
for i in lst:
sum = sum + (r/i)
total_amount_spent = 3*r
avg_cost = total_amount_spent/sum
print("Average Cost per year:",round(avg_cost,2))
CSET101-2023-Lab05-Thursday
1. You are given two different inputs of animal list. In the first list you are given name of the animal and in the
second list you are given weight of the animal you have to print the name of the animal whose weight is maximum
with the weight. If two or more than two animal have same weight the print the animal whose index is lesser.
Code:
lst1 = input().split()
lst2 = [int(x) for x in input().split()]
ind = lst2.index(max(lst2))
print("Animal is {} with weight of {}".format(lst1[ind],lst2[ind]))
2. You are given 10 numbers. Write a program to input integers in numbers list and create two lists
"Positive" and "Negative" where "Positive" contains only the positive numbers and "Negative" contains
only the negative numbers.
Format Input:
Input numbers split using space
Code:
Numbers= [int(x) for x in input().split()]
B=[]
C=[]
for i in Numbers:
if i >0:
B.append(i)
elif i < 0:
C.append(i)
else:
continue
2. You are given 10 numbers. Write a program to input integers in numbers list and create two lists
"Positive" and "Negative" where "Positive" contains only the positive numbers and "Negative" contains
only the negative numbers.
Format Input:
Input numbers split using space
Code:
Numbers= [int(x) for x in input().split()]
B=[]
C=[]
for i in Numbers:
if i >0:
B.append(i)
elif i < 0:
C.append(i)
else:
continue
3. Expenditure of a company(interests on loan in lac) is given for n years. What is the average amount
of interest per year which the company had to pay during this period?.
Write a program to take input for number of years (n), interests per year (list) and to calculate average amount of
interest per year (round average value till decimal’s two place).
Also print list of amount.
Input format:
N (number of years) .
List = [i1, i2, i3, i4 .. in] (interest on loan) .
4. You have given a list of integers with odd and even numbers in it. Your task is to count the number
of even elements and number of odd elements from list.
Code:
n = int(input())
lst = []
for i in range(n):
lst.append(int(input()))
even_count, odd_count = 0, 0
# iterating each number in list
for num in lst:
# checking condition
if num % 2 == 0:
even_count += 1
else:
odd_count += 1
5. Create two lists by taking inputs from the user. First input is number of elements and second input is
values in the list. Each list should only contain string as its member elements. Create a resultant list
such that this list contains the concatenation result of elements of first list with each element of second
list.
Code:
print("Enter the number of elements you want to add in first list")
l1 = int(input())
list1 = [ ]
print("Enter element value in the first list")
for i in range(l1):
list1.append(input())
print("Enter the number of elements you want to add in second list")
l2 = int(input())
list2 = [ ]
print("Enter element value in the second list")
for i in range(l2):
list2.append(input())
res_list=[]
for i in list1:
for j in list2:
res_list.append(i+j)
print(res_list)
6. Create a list by taking input from the user and which consists of only integer values. First input is the
number of elements, second is elements and third input is integer value named power. Suppose the list
created by us, has elements like elem1, elem2 … and so on. Create a resultant list where each element
value is modified as following:
[ elem1^power , elem2^power , elem3^power,….]
Code:
print("Enter the number of elements you want to add in the list")
n = int(input())
test_list = [ ]
print("Enter element value in the list")
for i in range(n):
test_list.append(int(input()))
print("Enter the value of variable named power")
power=int(input())
result_list = [ ]
for i in test_list:
result_list.append(i ** power)
print("The resultant list is:", result_list)
7. Create a list by taking input from the user. First input is the no. of elements you want to add in the list
and second input is the elements. Create a new list which is reverse of the existing list.
Code:
n = int(input())
list1 = []
for i in range(n):
list1.append(int(input()))
list2=list1[::-1]
print("Existing List:", list1)
print("Resultant list:", list2)
8. Create a list by taking input from the user and which consists of only integer values. First input is the
size of the list and second input is the values in the list. Find the sum of all elements in the list.
Code:
n = int(input())
test_list = []
for i in range(n):
test_list.append(int(input()))
sum_numbers=0
for x in test_list:
sum_numbers += x
print("sum of elements in the given list is:", sum_numbers)
CSET101-2023-Lab05-Friday
1. Create a list by taking input from the user. First input is the number of elements to insert and second input is the
value of elements. Write a program to swap first and last values of the list.
Code:
size = int(input("Enter the number of elements you want to add in the list"))
lst = []
print("Enter element value in the list")
for i in range(size):
lst.append(int(input()))
print("Original list is:", lst)
temp=lst[0]
lst[0]=lst[size-1]
lst[size-1]=temp
print("Resultant list is:",lst)
2. You are building an online shopping cart. Implement a program that checks if a product is
in the cart using a list.
Code:
shopping_cart = list(input().split(" "))
product = input("product name: ")
if product in shopping_cart:
print("Product is in the cart")
else:
print("Product is not in the cart")
3. You are tasked with creating a simple to-do list application. Write a Python program that
allows users to add tasks to their to-do list and then display the entire list.
Code:
todo_list = []
def add_task(task):
todo_list.append(task)
def display_list():
for index, task in enumerate(todo_list, start=1):
print(f"{index}. {task}")
n=int(input())
for i in range(n):
add_task(input("task: "))
display_list()
4. Create a program that simulates a shopping list. The user should be able to add items to
the list, remove items, and view the list.
Code:
shopping_list = []
def add_item(item):
shopping_list.append(item)
def remove_item(item):
if item in shopping_list:
shopping_list.remove(item)
else:
print(f"{item} not found in the shopping list.")
def view_list():
print("Shopping List:")
for item in shopping_list:
print(item)
while True:
print("1. Add Item")
print("2. Remove Item")
print("3. View List")
print("4. Exit")
if choice == 1:
item = input("Enter item to add: ")
add_item(item)
elif choice == 2:
item = input("Enter item to remove: ")
remove_item(item)
elif choice == 3:
view_list()
elif choice == 4:
break
else:
print("Invalid choice. Please try again.")
5. Create a program that allows the user to manage a to-do list. The user should be able to
add tasks, mark tasks as complete, and view the list.
Code:
todo_list = []
def add_task(task):
todo_list.append({"task": task, "completed": False})
def complete_task(task):
for t in todo_list:
if t["task"] == task:
t["completed"] = True
break
else:
print(f"{task} not found in the to-do list.")
def view_list():
print("To-Do List:")
for t in todo_list:
status = "Completed" if t["completed"] else "Not Completed"
print(f"{t['task']} - {status}")
while True:
print("1. Add Task")
print("2. Complete Task")
print("3. View List")
print("4. Exit")
if choice == 1:
task = input("Enter task to add: ")
add_task(task)
elif choice == 2:
task = input("Enter task to complete: ")
complete_task(task)
elif choice == 3:
view_list()
elif choice == 4:
break
else:
print("Invalid choice. Please try again.")
7. Write a Python program to find the maximum and minimum numbers in a given list.
Code:
def find_max_min(numbers):
if not numbers:
return None, None
max_num = min_num = numbers[0]
for num in numbers:
if num > max_num:
max_num = num
elif num < min_num:
min_num = num
return max_num, min_num
8. Write a Python program to find the sum and average of numbers in a given list.
Code:
def calculate_sum_average(numbers):
if not numbers:
return None, None
total_sum = sum(numbers)
average = total_sum / len(numbers)
return total_sum, average
1.In formal language theory and computer science, a substring is a contiguous sequence of
characters within a string. For example, substring for “abc” is {a, b, c, ab, bc, abc}. Write a Python
function to count the total number of vowels present in all substring of a given string.
TC1
Input:
Naina #string
Output:
22 #Total number of vowels in all substring
TC2
Input:
Enter a string: abc
Output:
Total number of vowels in all substring is: 3
TC3
Input:
Enter a string: Bennett
Output:
Total number of vowels in all substring is: 27
Hint:
Naive Approach: Given a string of length N, the number of substrings that can be
formed=N(N+1)/2. A simple solution is for each substring, we count the occurrences of the vowels
and add them to get the result. The time complexity of this approach is O(N 3) which is not suitable
for large values of N.
Efficient Approach: The idea is to use a prefix sum array-based technique where we store the
occurrences of each character in all the substrings concatenated.
● For the first character,
no. of substrings starting with that character + the number of substrings formed by the previous
characters containing this character – the number of substrings formed by the previous characters
only.
Solution:
def sumVowel(string):
n = len(string)
sum = 0
string = string.lower()
return sum
2.Design and code a function viz., “perfect()” that determines if parameter number is a perfect
number. Use this function in a program that determines and prints all the perfect numbers between 1
and N in a list.
[An integer number is said to be “perfect number” if its factors, including 1(but not the number
itself), sum to the number. E.g., 6 is a perfect number because 6=1+2+3].
Code:
def perfect(n):
sum = 0
for i in range(1,n):
if n%i == 0:
sum+=i
if sum == n:
return True
else:
return False
3.Write a Python module to design a system where any binary string would be taken as input and
flips every bit after getting first bit as 1 when traverse from the right.
Code: tows_complement.py
def TwoScomplement(str):
n = len(str)
main2.py
from tows_complement import *
print("Enter any binary string: ")
str = input()
print(TwoScomplement(str))
Test Case 1
Input:
Enter any binary string:
10010101
Output:
01101011
Test Case 2
Input:
Enter any binary string:
101
Output:
011
Test Case 3
Input
Enter any binary string:
101
Output:
011
Test Case 4
Input
Enter any binary string:
111
Output:
001
4. Maths has various fields and trigonometry is one of them. It has never been so easy until I knew
about the various in-built maths functions provided in Python. Now you tell me a number and I will
answer the following calculations in seconds:
1) Cosine value of ‘n’
2) Sine value of ‘n’
3) Angle from radian to degree
4) Degree to radians
Test Case 1
Input:
0
Output:
Cosine of 0 is 1.0
Sine of 0 is 0.0
Radian to degree of 0 is 0.0
Degree to radian of 0 is 0.0
Test Case 2
Input
1
Output
Cosine of 1 is 0.5403023058681398
Sine of 1 is 0.8414709848078965
Radian to degree of 1 is 57.29577951308232
Degree to radian of 1 is 0.017453292519943295
Test Case 3
Input:
30
Output:
Cosine of 30 is 0.15425144988758405
Sine of 30 is -0.9880316240928618
Radian to degree of 30 is 1718.8733853924696
Degree to radian of 30 is 0.5235987755982988
Solution:
import math
n=int(input())
print("Cosine of {} is {}".format(n,math.cos(n)))
print("Sine of {} is {}".format(n,math.sin(n)))
5.Python supports various types of arguments that can be passed at the time of the function call. A
default argument is a parameter that assumes a default value if a value is not provided in the
function call for that argument. Calculate area of rectangle by providing the input length and
breadth. If breadth is not passed to the function it takes the value 50 by default.
Code:
l = int(input())
b=int(input())
def myFun(l, b=50):
print("l:", l)
print("b:", b)
print("l*b:", l*b)
Test Case 2
Input:
0
4
Output:
Only l is passed:
('l:', 0)
('b:', 50)
('l*b:', 0)
l and b both is passed:
('l:', 0)
('b:', 4)
('l*b:', 0)
Test case 3:
input:
10
20
Output:
Only l is passed:
('l:', 10)
('b:', 50)
('l*b:', 500)
l and b both is passed:
('l:', 10)
('b:', 20)
('l*b:', 200)
Test Case 4:
input:
20
30
Output:
Only l is passed:
('l:', 20)
('b:', 50)
('l*b:', 1000)
l and b both is passed:
('l:', 20)
('b:', 30)
('l*b:', 600)
1. After seeing the pollution level, Kejriwal gave the concept of even and odd. So as per the rule,
one day vehicle with even number plates were allowed and another day vehicle with odd number
plates were allowed. For this, weekdays were assigned numbers starting from ‘1,2,,..7’ and so on.
Write a program to decide that on which day vehicle with even number plates will be allowed and
on which day vehicle with odd number plates will be allowed? (Take 1-Sunday, 2-Monday, 3-
Tuesday, 4-Wednesday, 5-Thrusday, 6-Friday and 7-Saturday.
Test Cases:
Test Case 1:
Sunday
Output:
Enter day: Sunday
Vehicle with odd number plates are allowed
Test Case 2:
Wednesday
Output:
Enter day: Wednesday
Vehicle with even number plates are allowed
Test Case 3:
Saturday
Output:
Enter day: Saturday
Vehicle with odd number plates are allowed
Test Case 4:
Friday
Output:
Enter day: Friday
Vehicle with even number plates are allowed
Solution:
def evenodd( x ):
if (x % 2 == 0):
print ("Vehicle with even number plates are allowed")
else:
print ("Vehicle with odd number plates are allowed")
x=input("Enter day: ")
print(x)
if x=='Sunday':
evenodd(1)
if x=='Monday':
evenodd(2)
if x=='Tuesday':
evenodd(3)
if x=='Wednesday':
evenodd(4)
if x=='Thursday':
evenodd(5)
if x=='Friday':
evenodd(6)
if x=='Saturday':
evenodd(7)
2. Design a temperature converter to convert from one system (i.e. Centigrade) to other system
(Fahrenheit) and vice-versa. Do this problem using Python modules where inputs would be any
number entered by user and the target system, entered by the same user.
Use the formula 5 * (x - 32) / 9.0 from fahrenheit to centigrade. Use the formula 9 * x / 5.0 + 32
from centigrade to fahrenheit.
Code:
temp_conversion.py
# function to convert F to C
def to_centigrade(x):
return 5 * (x - 32) / 9.0
# function to convert C to F
def to_fahrenheit(x):
return 9 * x / 5.0 + 32
main1.py
from temp_conversion import *
Test Case 1
Input:
Enter a number:
11
Output:
Enter the system to be converted; C for Centigrade, F for Fahrenheit:
C
Equivalent temperature in Centigrade is -11.67
Test Case 2
Input:
Enter a number:
21
Output:
Enter the system to be converted; C for Centigrade, F for Fahrenheit:
F
Equivalent temperature in Fahrenheit is 69.80
Test case 3
Input:
Enter a number:
45
Output:
Enter the system to be converted; C for Centigrade, F for Fahrenheit:
F
Equivalent temperature in Fahrenheit is 113.00
Test Case 4
Input:
Enter a number:
45
Output:
Enter the system to be converted; C for Centigrade, F for Fahrenheit:
C
Equivalent temperature in Centigrade is 7.22
3.Write a program to find the sum of all the perfect numbers between 1 and N. First you need to
design and code a function named “perfect()” that determines if a given number is a perfect number
or not. Use this function in a program that determines and prints all the perfect numbers between 1
and N and also stores it in a list. Second, you need to add all the numbers of the list.
[An integer number is said to be “perfect number” if its factors, including 1(but not the number
itself), sum to the number. E.g., 6 is a perfect number because 6=1+2+3].
Code:
def perfect(n):
sum = 0
for i in range(1,n):
if n%i == 0:
sum+=i
if sum == n:
return True
else:
return False
print("Enter the value of N: ")
N = int(input())
lst = []
for i in range(1,N+1):
if perfect(i):
lst.append(i)
print("Perfect numbers are: ", lst)
def sumperfect(a):
sump = 0
for i in a:
sump += i
return sump
4.Write a function to calculate the LCM of two positive integers (M, N) by factorizing each number
by their prime factors. Don’t use math library functions to calculate GCD or LCM.
Input (Input sequence M, N):
20
30
Output:
60
Input:
12
36
Output:
36
Input:
1
19
Output:
19
Input:
0
10
Output:
0
Input:
40
23
Output:
920
Input:
11
29
Output:
319
Input:
9
8
Output:
72
Program:
def isprime(n):
f=True
for i in range(2,(int(n**0.5))+1):
if n%i==0:
f=False
break
return f
def LCM(a,b):
N=a
M=b
La=[]
Lb=[]
L=[]
limit1=(int(a**0.5))+2
limit2=(int(b**0.5))+2
while a>1 :
if isprime(a):
La.append(a)
break
for j in range(2, limit1):
if a%j==0 and isprime(j):
La.append(j)
a=a//j
break
while b>1 :
if isprime(b):
Lb.append(b)
break
for j in range(2, limit2):
if b%j==0 and isprime(j):
Lb.append(j)
b=b//j
break
for i in La:
if i in Lb:
L.append(i)
Lb.remove(i)
#print(L)
m=1
for i in L:
m=m*i
#print(i,m)
return (N*M)//m
a=int(input())
b=int(input())
print(LCM(a,b))
5. A professor writes some sentences on whiteboard in a classroom and asks his students to design a
function in Python to extract even length words in a list from the given sentences.
TC1
Input:
Enter sentences (exclude stop symbol):
This is a Python function to extract even length words
Output:
Extracted even length words are: ['This', 'is', 'Python', 'function', 'to', 'even', 'length', 'words.']
TC2
Input:
Enter sentences:
Enter sentences:
In Python, for loop is used to print the various patterns. Printing the various patterns are most
common asked programming questions in the interview. The multiple for loops are used to print the
patterns where the first outer loop is used to print the number of rows, and the inner loop is used to
print the number of columns. Most of the patterns use the following concepts.
Output:z
Extracted even length words are: ['In', 'loop', 'is', 'used', 'to', 'Printing', 'patterns', 'most', 'common',
'in', 'interview.', 'multiple', 'used', 'to', 'patterns', 'loop', 'is', 'used', 'to', 'number', 'of', 'loop', 'is', 'used',
'to', 'number', 'of', 'columns.', 'Most', 'of', 'patterns']
TC3
Input:
Enter sentences:
Please write comments if you find anything incorrect, or you want to share more information about
the problem
Output:
Extracted even length words are: ['Please', 'comments', 'if', 'find', 'anything', 'incorrect,', 'or', 'want',
'to', 'more']
Solution:
def Even_Len_Words(s):
s = s.split(' ')
even = []
for word in s:
if len(word)%2==0:
even.append(word)
return even
# Driver Code
print("Enter sentences: ")
s = input()
lst = Even_Len_Words(s)
print("Extracted even length words are: ", lst)
6.Counting Upper and Lower case and Space symbols: Design a python module that will count both
upper, lower case symbols, and spaces in a given paragraph or sentences. Create a module named
case_counting.py which has the funtion string_test for performing the count. Create an other
program file main.py which import the case_counting module.
Code
case_counting.py
def string_test(s):
d={"UPPER_CASE":0, "LOWER_CASE":0, "Spaces":0}
for c in s:
if c.isupper():
d["UPPER_CASE"]+=1
elif c.islower():
d["LOWER_CASE"]+=1
elif c.isspace():
d["Spaces"]+=1
else:
pass
main.py
from case_counting import *
print("Enter any sentence:")
str = input()
string_test(str)
Test Case 1
Input:
Enter any sentence:
Pollution is very high in Delhi-NCR
Output:
Original String: Pollution is very high in Delhi-NCR
No. of Upper case characters: 5
No. of Lower case Characters: 24
No. of spaces: 5
Test Case 2
Input:
Enter any sentence:
BeNNett uNiversity Greater Noida
Output:
Original String: BeNNett uNiversity Greater Noida
No. of Upper case characters: 6
No. of Lower case Characters: 23
No. of spaces: 3
Test Case 3:
Input:
Enter any sentence:
This is program to create Module in Python
Output:
Original String: This is program to create Module in Python
No. of Upper case characters: 3
No. of Lower case Characters: 32
No. of spaces: 7
Test Case 4:
Input:
Enter any sentence:
You should always practice the programming ethics
Output:
Original String: You should always practice the programming ethics
No. of Upper case characters: 1
No. of Lower case Characters: 42
No. of spaces: 6
1. A lady went to astrologer for her future prediction. The astrologer instead of asking the date of
birth asked the lady the day she was born on! The lady had no idea that what was the day when she
was born. She asked her son how it could be found now?? His son was smart enough to write a
program in python that displays the calendar of the month of a given year. You too can be smart
enough by doing the same by using inbuilt function for printing the calendar.
Test Case 1:
Input:
1986
12
Output:
Enter year: 1986
Enter month: 12
December 1986
Mo Tu We Th Fr Sa Su
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
Test Case 2:
Input
2020
12
Output:
Enter year: 2020
Enter month: 12
December 2020
Mo Tu We Th Fr Sa Su
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Solution:
import calendar
print(calendar.month(yy,mm))
2. Write program to assist in password setting for login in web portal with certain specifications for
strong password.
● The password must be at least 8 characters long.
● The password must contain uppercase character
● The password must contain, lower case character.
● The password must contain digit.
● The password must contain special characters among ['!', '@', '#', '$', '&']
Given a password by the user, your program should accept or reject the password based on the
specifications.
Input:
12abscer!efgA
Output:
Password accepted
Input:
AD#wdf45
Output:
Password accepted
Input:
12ab!A
Output:
Password rejected
Input:
12ab!@efgh
Output:
Password rejected
Input:
12AB!@EFGH
Output:
Password rejected
Input:
cdAB!@EFGH
Output:
Password rejected
Input:
12abscer !efgA
Output:
Password rejected
Program:
def checklength(s):
if len(s)>=8:
return True
else:
return False
def ifcapital(s):
for i in s:
if 'A'<=i<='Z':
return True
return False
def ifsmall(s):
for i in s:
if 'a'<=i<='z':
return True
return False
def ifnumeric(s):
for i in s:
if '0'<=i<='9':
return True
return False
def ifspecial(s,l):
for i in s:
if i in l:
return True
return False
def checkoverall(s):
for i in s:
if ('A'<=i<='Z') or ('a'<=i<='z') or ('0'<=i<='9') or (i in ['!','@','#','$','&']):
pass
else:
return False
return True
p=input()
v=checklength(p) and ifcapital(p) and ifsmall(p) and ifnumeric(p) and ifspecial(p,['!','@','#','$','&'])
and checkoverall(p)
if v:
print('Password accepted')
else:
print('Password rejected')
Code:
temp_conversion.py
# function to convert F to C
def to_centigrade(x):
return 5 * (x - 32) / 9.0
# function to convert C to F
def to_fahrenheit(x):
return 9 * x / 5.0 + 32
main1.py
from temp_conversion import *
Test Case 1
Input:
Enter a number:
11
Output:
Enter the system to be converted; C for Centigrade, F for Fahrenheit:
C
Equivalent temperature in Centigrade is -11.67
Test Case 2
Input:
Enter a number:
21
Output:
Enter the system to be converted; C for Centigrade, F for Fahrenheit:
F
Equivalent temperature in Fahrenheit is 69.80
Test case 3
Input:
Enter a number:
45
Output:
Enter the system to be converted; C for Centigrade, F for Fahrenheit:
F
Equivalent temperature in Fahrenheit is 113.00
Test Case 4
Input:
Enter a number:
45
Output:
Enter the system to be converted; C for Centigrade, F for Fahrenheit:
C
Equivalent temperature in Centigrade is 7.22
4.Write a program to find the multiplication of all the perfect numbers between 1 and N. First you
need to design and code a function named “perfect()” that determines if a given number is a perfect
number or not. Use this function in a program that determines and prints all the perfect numbers
between 1 and N and also stores it in a list. Second, you need to multiply all the numbers of the list.
[An integer number is said to be “perfect number” if its factors, including 1(but not the number
itself), sum to the number. E.g., 28 is perfect as 1 + 2 + 4 + 7 + 14 = 28].
Code:
def perfect(n):
sum = 0
for i in range(1,n):
if n%i == 0:
sum+=i
if sum == n:
return True
else:
return False
print("Enter the value of N: ")
N = int(input())
lst = []
for i in range(1,N+1):
if perfect(i):
lst.append(i)
print("Perfect numbers are: ", lst)
def summulperfect(a):
sump = 1
for i in a:
sump *= i
return sump
5.In a college fest, an event “coderider” was organized. In this, the candidate was to reverse the
given word. It was a great fun and everybody enjoyed the event. Now automate this event by
writing a function to reverse a string.
Test Cases:
Test Case 1:
Input: Enjoy this lab
Output:
Given String: Enjoy this lab
Reversed String: bal siht yojnE
Test Case 2:
Input: Madam
Output:
Given String: Madam
Reversed String: madam
Solution:
def reverse(str):
s = ""
for ch in str:
s = ch + s
return s
# given string
mystr =str(input())
# reversed string
6. One of the parents, in a family, gives a number N and asks his child to extract list of those
numbers that are both squared and cube of some numbers but should be bounded by N. Also, find
total such numbers.
TC1
Input:
Enter the number:
1000
Output:
Desired numbers are [1, 64, 729] and total count is 3
TC2
Input:
Enter the number:
5000
Output:
Desired numbers are [1, 64, 729, 4096] and total count is 4
TC3
Input:
Enter the number:
50000
Output:
Desired numbers are [1, 64, 729, 4096, 15625, 46656] and total count is 6
Hint:
For a given positive number N to be a perfect square, it must satisfy P2 = N Similarly, Q3 = N for a
perfect cube where P and Q are some positive integers.
N = P2 = Q 3
Thus, if N is a 6th power, then this would certainly work. Say N = A6 which can be written
as (A3)2 or (A2)3.
So, pick 6th power of every positive integer which is less than equal to N.
Solution:
def SquareCube(N):
cnt, i = 0, 1
lst = []
while (i ** 6 <= N):
lst.append(i**6)
cnt += 1
i += 1
1. Two sets of questions papers are made for a batch. The sets are distributed with respect to roll no.
Students with odd roll numbers are provided to solve set one and the students having even roll
numbers are provided to solve set 2. Write a program to check the roll no of a student and decide
the set number.
Test Cases:
Test Case 1:
Input: 12
Output: Roll number:12
Even roll number, set 2 is given
Test Case 2:
Input: 15
Output: Roll number:15
Odd roll number, set 1 is given
Solution:
def evenOdd( x ):
if (x % 2 == 0):
print("Even roll number, set 2 is given")
else:
print("Odd roll number, set 1 is given")
x=int(input("Roll number:"))
print(x)
evenOdd(x)
2. Five friends are returning from an outing. They see an old woman begging, since they have
enjoyed all day and now everyone is short of money. They collect their money sum them up and
give it to the old women. Write a function to sum up the money of all five friends and display the
total amount paid to the old women.
Test Cases:
Test Case 1
Input:10
20
20
100
50
Output: Total money collected is: 200
Test Case 2:
Input:10.50
20.50
100.30
10
10
Output: Total money collected is: 151.3
Solution:
def listsum(lst):
theSum = 0
for i in lst:
theSum = theSum + i
return theSum
lst = []
n=5
for i in range(0,n):
numlist=eval(input())
lst.append(numlist)
print("Total money collected is:", listsum(lst))
Write a python program which import the above created module into it and call the two methods by
passing a number and a choice for formula 1 or 2. We are saying that Formula 1 is converting
fahrenheit to centigrade and formula 2 is converting centigrade to fahrenheit.
Note: Formula 1 and 2 given in the question is not the actual formula.
Code:
temp1_conversion.py
# function to convert F to C
def to_centigrade(x):
return 7 * (x**2 + 12) / 5.0
# function to convert C to F
def to_fahrenheit(x):
return 7 * x**2 / 5.0 - 32
main12.py
from temp1_conversion import *
Test Case 2
Input:
Enter a number:
45
Enter the system to be converted; C for Centigrade, F for Fahrenheit:
F
Output:
Equivalent temperature in Fahrenheit is 2803.00
Test case 3
IEnter a number:
34
Enter the system to be converted; C for Centigrade, F for Fahrenheit:
C
Output:
Equivalent temperature in Centigrade is 1635.20
Test Case 4
Input:
Enter a number:
0
Enter the system to be converted; C for Centigrade, F for Fahrenheit:
F
Output:
Equivalent temperature in Fahrenheit is -32.00
4. Write a Python program to calculate the area of a rectangle using nested functions.
def calculate_rectangle_area(length, width):
def multiply(x, y):
return x * y
area = multiply(length, width)
return area
output
Enter length: 7
Enter width: 8
Rectangle area: 56.0
5.During a game, contestant is asked to tell the names of hit movies and as soon as the director says
‘cut’, the contestant stops and the list of the names of the movies are displayed. Write a user defined
function by the name director_cut() that takes list as an argument and this job.
Test Case 1:
PS I love You
Coco
Sholay
Output:
['PS I love you', 'Coco', 'Sholay']
Test Case 2:
Joker
The Dark Night
Bahubali
Anand
Cut
Output:
['Joker', 'The Dark Night', 'Bahubali', 'Anand']
Test Case 3:
Dark 7 White
chernobyl
Cut
Output
['Dark 7 White ', 'chernobyl ']
Solution:
def director_cut(a):
while True:
n=input()
if n=='cut' or n=='Cut':
break
else:
a.append(n)
return a
a=[]
print(director_cut(a))
6.While distributing the sweets Rohan on his birthday found that at the end of the distribution he
was running in short of sweets. Though, he got 1 sweet for every classmate. He then realized that
somebody had taken the sweet more than once. He reported this issue to the class teacher. To avoid
such things the teacher made a rule that once the student had taken the sweet his roll no will be
recorded in a list. Thus, if at the end there is any duplicacy in the roll number in the list then ‘False’
is called out else ‘True’. Write a function that does the same i.e returns ‘True’ if the list contains all
unique numbers else returns ‘False’.
TC1
Input:
Enter length of list: 5
21
1
45
25
10
Output:
[21, 1, 45, 25, 10]
True
TC2
Input:
Enter length of list: 8
-1
23
45
23
-45
9
0
512
Output:
[-1, 23, 45, 23, -45, 9, 0, 512]
False
TC3
Input:
Enter length of 1st list: 4
5
9
6
8
Output:
[5, 9, 6, 8]
True
Solution:
L1=[]
n=int(input("Enter length of 1st list: "))
print(n)
for i in range(n):
no=int(input())
L1.append(no)
print(L1)
def test_distinct(data):
if len(data) == len(set(data)):
return True
else:
return False;
print(test_distinct(L1))
1. A teacher, in play school, is teaching a child to identify upper case and lower case letters.
She gave some sentence and asked the child to count the number of both types of characters.
Can you write a function to implement the same?
TC1
Input:
Enter any sentence: Today is WeDnesDay
Output:
Original String: Today is WeDnesDay
No. of Upper case characters: 4
No. of Lower case Characters: 12
TC2
Input:
Enter any sentence: The quick Brown Fox
Output:
Original String: The quick Brown Fox
No. of Upper case characters: 3
No. of Lower case Characters: 13
TC3
Input:
Enter any sentence: I lovE My IndiA And I LIVE here
Output:
Original String: I lovE My IndiA And I LIVE here
No. of Upper case characters: 11
No. of Lower case Characters: 13
Solution:
def string_test(s):
d={"UPPER_CASE":0, "LOWER_CASE":0}
for c in s:
if c.isupper():
d["UPPER_CASE"]+=1
elif c.islower():
d["LOWER_CASE"]+=1
else:
pass
print ("Original String:", s)
print ("No. of Upper case characters:", d["UPPER_CASE"])
print ("No. of Lower case Characters:", d["LOWER_CASE"])
2. You are creating a calendar project in which the days between any two dates are required to be
calculated. Write a program which will take two dates(dd:mm:yyyy format) as inputs and output the
number days between the two dates. Don’t use any inbuild function for date processing and
calculation
Input:
10:01:2096
06:05:2105
Output:
3403
Input:
12:04:1996
16:01:2006
Output:
3566
Input:
12:01:2020
06:01:2021
Output:
360
Input:
12:03:2020
06:01:2021
Output:
300
Program:
def isleapyear(y):
if y%400==0:
return True
elif y%100==0:
return False
if y%4==0:
return True
else:
return False
def day_in_year(d,m,y):
'''it computes the day number in the year among the 365 days'''
lp=int(isleapyear(y))#this adds a day if leap year
D=0
if m==1:
D=d
if m==2:
D=31+d
if m==3:
D=31+28+lp+d
if m==4:
D=d+lp+31+28+31
if m==5:
D=d+lp+31+28+31+30
if m==6:
D=d+lp+31+28+31+30+31
if m==7:
D=d+lp+31+28+31+30+31+30
if m==8:
D=d+lp+31+28+31+30+31+30+31
if m==9:
D=d+lp+31+28+31+30+31+30+31+31
if m==10:
D=d+lp+31+28+31+30+31+30+31+31+30
if m==11:
D=d+lp+31+28+31+30+31+30+31+31+30+31
if m==12:
D=d+lp+31+28+31+30+31+30+31+31+30+31+30
return D
def days(s1,s2):
d1=int(s1[:2])
m1=int(s1[3:5]) #10:05:2020
y1=int(s1[6:])
d2=int(s2[:2])
m2=int(s2[3:5])
y2=int(s2[6:])
D1=day_in_year(d1,m1,y1)
D2=day_in_year(d2,m2,y2)
D=D2-D1
for y in range(y1,y2):
lp=int(isleapyear(y))
D=D+365+lp
return D
date1=input()
date2=input()
print(days(date1,date2))
3. Implement the following algorithm, which is to print all the elements of the power set of a given
set. The power set is the set of all subsets of a set. For example a set S is {A,B,C}, then power set
is {{},{A},{B},{C},{A,B},{B,C},{C,A},{A,B,C}}.
Algorithm:
Test Case 1
Input:
"['A','B']"
Output:
[]
['A']
['B']
['A', 'B']
Test Case 2
Input:
"[]"
Output:
[]
Test case 3
Input:
"['h']"
Output:
[]
['h']
Test Case 4
Input:
"[1, 2]"
Output:
[]
[1]
[2]
[1, 2]
Code:
def power_set(s):
# Base case: the power set of an empty list is a list with an empty list
if len(s) == 0:
return [[]]
# Combine the first element with the power set of the remaining elements
new_set = []
for subset in remaining_power_set:
new_set.append(subset)
new_set.append([elem] + subset)
return new_set
# Test
lst = eval(input())
for subset in power_set(lst):
print(subset)
4.While taking an exam the teacher asked the students to print the first n Natural Numbers
(Natural), Even Numbers (Even) and Odd Numbers (Odd) as per the user choice. The objective
behind this program was to explain the usage of different paraments in range function. Write a
program in python to help the teacher to explain the students the different arguments used in range
function. To print the numbers, take the type of numbers and the limit till where you want to print.
Test Case 1:
Input:
Natural
20
Output:
Print: Natural
Till range: 20
Natural Numbers till 20 are:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
Test Case 2:
Input:
Odd
30
Output:
Print: Odd
Till range: 30
Odd Numbers till 30 are:
1 3 5 7 9 11 13 15 17 19 21 23 25 27 29
Test Case 3:
Input:
Even
40
Output:
Print: Even
Till range: 40
Even Numbers till 40 are:
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40
Test Case 4:
Input:
xyz
10
Output:
Print: xyz
Till range: 10
Wrong Choice
Solution:
x=input("Print: ")
print(x)
n=int(input("Till range: "))
print(n)
if x=='Natural':
print("Natural Numbers till {} are:".format(n))
for i in range(n+1):
print(i, end =" ")
print("\n")
elif x=='Odd':
print("Odd Numbers till {} are:".format(n))
for i in range(1,n+1,2):
print(i, end =" ")
elif x=='Even':
print("Even Numbers till {} are:".format(n))
for i in range(2,n+1,2):
print(i, end =" ")
else:
print("Wrong Choice")
5.Write a function which will receive a list of numeric values, changes the negative values to
corresponding positive values (example: -5 will be changed to 5) and returns the changed list. After
receiving the changed list, display the original list, the changed list along with the number of places
where the changed list is different from the original list.
Input:
[1,2,-3,8,5,6,0,9]
Output:
[1, 2, -3, 8, 5, 6, 0, 9]
[1, 2, 3, 8, 5, 6, 0, 9]
1
Input:
[-3,2,3,4,5,-1,0,10,-20]
Output:
[-3, 2, 3, 4, 5, -1, 0, 10, -20]
[3, 2, 3, 4, 5, 1, 0, 10, 20]
3
Program:
def fun(l):
import random
for i in range(len(l)):
if l[i]<0:
l[i]=-l[i]
return l
l=eval(input())
l1=fun(l[:])
cnt=0
for i in range(len(l)):
if l[i]!=l1[i]:
cnt=cnt+1
print(l)
print(l1)
print(cnt)
6.You are given a sequence of words, hyphen(-) as a separator between two words. Write a Python
program to sort the words alphabetically.
TC1
Input:
Enter the sequence of words with - as separator: green-red-black-white
Output:
black green red white
TC2
Input:
Enter the sequence of words with - as separator: I-am-Going-to-School
Output:
am going i school to
TC3
Input:
Enter the sequence of words with - as separator: Go-To-school-Towards-study
Output:
go school study to towards
Solution:
def word_sorting(S):
W = []
W = S.split("-")
for i in range(len(W)):
W[i]=W[i].lower()
S = sorted(W)
print(" ".join(S))
word_sorting(S)
1.Write a recursive function which will receive a list of numbers (L) and a sum (S) and displays all
such subsists of L which have S as the summation of all their elements. For an example L=[2,5,4,7]
and S=11, it should display solution exists (as [2,5,4] and [4,7] are two solutions). If no sub-lists
have addition of all its elements equals to S, then it should display, no solution exists.
Code:
def sub_sum(L,d,P=[],l=0):
sol=[]
if l==len(L):
for i in P:
if sum(i)==d:
sol.append(i)
return P,sol
elif l==0:
l=l+1
for i in range(len(L)):
P.append([L[i]])
return sub_sum(L,d,P,l)
else:
l=l+1
for p in P:
for i in range(len(L)):
if L[i] not in p:
L1=p+[L[i]]
L1.sort()
if L1 not in P:
P.append(L1)
return sub_sum(L,d,P,l)
print("Enter a list, for example [1,2,3,4] ")
L=eval(input())
print("Enter sum: ")
s=int(input())
L1,S=sub_sum(L,s)
if len(S)==0:
print('No Solution exists')
else:
print('Solution exists')
Test Case 1
Input:
Enter a list, for example [1,2,3,4]
[2,6,8,9]
Enter sum:
8
Output:
Solution exists
Test Case 2
Input:
Enter a list, for example [1,2,3,4]
[1,2,3,4]
Enter sum:
5
Output:
Solution exists
Test Case3
Input:
Enter a list, for example [1,2,3,4]
[2,4,5,7]
Enter sum:
10
Output:
No Solution exists
Test Case 4
Input
Enter a list, for example [1,2,3,4]
[2,5,7,4]
Enter sum:
11
Output:
Solution exists
2. In mathematics, a perfect power is a natural number that is a product of equal natural factors,
or, in other words, an integer that can be expressed as a square or a higher integer power of
another integer greater than one. More formally, n is a perfect power if there exist natural
numbers m > 1, and k > 1 such that mk = n. In this case, n may be called a perfect kth power. If
k = 2 or k = 3, then n is called a perfect square or perfect cube, respectively. Write a recursive
function which receives two arguments; X and b and checks whether X is the prefect power of
b, i.e, X=b**k, where k is a positive integer. Both X and b are non-zero positive integers. The
recursive function should return a number which is perfect power of b and less than or equals to
X, if X is not a perfect power of b.
Code:
def if_power(N,d,t=True,p=0):
if N==1:
return t and True, d**p
elif N==d:
return t and True, d**(p+1)
elif N<d:
return t and False, d**p
elif N%d==0:
return if_power(N//d,d,t and True, p+1)
else:
return if_power(N//d,d,t and False, p+1)
N=int(input())
d=int(input())
Tv,n=if_power(N,d)
if Tv:
print('{} is perfect power of {}'.format(N,d))
else:
print('{} is not a perfect power of {}'.format(N,d))
print('Nearest power is {}'.format(n))
Test case 1:
Input:
625
5
Output:
625 is perfect power of 5
Test case 2:
Input:
243
3
Output:
243 is perfect power of 3
Test case 3:
Input:
72
4
Output:
72 is not a perfect power of 4
Nearest power is 64
Test case 4:
Input:
600
6
Output:
600 is not a perfect power of 6
Nearest power is 216
students_list=[]
n=int(input("Provide total number of students"))
for i in range(n):
if(i==0):
students_list.append({"name":str(input("Enter name of "+str(i+1)+" st
student")),"age":int(input("Enter age of "+str(i+1)+" st student"))})
elif(i==1):
students_list.append({"name":str(input("Enter name of "+str(i+1)+" nd
student")),"age":int(input("Enter age of "+str(i+1)+" nd student"))})
elif(i==2):
students_list.append({"name":str(input("Enter name of "+str(i+1)+" rd
student")),"age":int(input("Enter age of "+str(i+1)+" rd student"))})
else:
students_list.append({"name":str(input("Enter name of "+str(i+1)+" th
student")),"age":int(input("Enter age of "+str(i+1)+" th student"))})
students_list.sort(key=lambda x: x["age"])
print("Sorted students by age:")
for student in students_list:
print(student)
output 1:
Provide total number of students5
Enter name of 1 st studentSidharth
Enter age of 1 st student12
Enter name of 2 nd studentAjay
Enter age of 2 nd student11
Enter name of 3 rd studentVishal
Enter age of 3 rd student10
Enter name of 4 th studentArun
Enter age of 4 th student16
Enter name of 5 th studentVikas
Enter age of 5 th student15
Sorted students by age:
{'name': 'Vishal', 'age': 10}
{'name': 'Ajay', 'age': 11}
{'name': 'Sidharth', 'age': 12}
{'name': 'Vikas', 'age': 15}
Output 2:
Output 1:
Enter total number of elements3
Enter value of 1 st element1
Enter value of 2 nd element2
Enter value of 3 rd element3
Total sum of squares: 14
Output 2:
Enter total number of elements5
Enter value of 1 st element0
Enter value of 2 nd element1
Enter value of 3 rd element-1
Enter value of 4 th element2
Enter value of 5 th element-2
Total sum of squares: 10
output 1:
Provide list of elements being seperated by white spaces1 12 123
Maximum length of strings: 3
Output 2:
Provide list of elements being seperated by white spacesa ab abc abcd
Maximum length of strings: 4
Maximum length of strings: 6
6. The game of ring exchange between rods is played in a college. In this game, there are three rods
and a number of disks of different sizes, which can slide onto any rod. Initially, this game starts
where disks are arranged in ascending order of size on one rod (making a conical shape), the
smallest at the top. Now these disks are to be shifted to another rod by following certain rules:
1. Only one disk can be moved at a time.
2. Each move consists of taking the upper disk from one of the rods and placing it on top of
another rod or on an empty rod.
3. No larger disk may be placed on top of a smaller disk.
4. If n<0 the print “At-least Give one Disk”
Code:
def TowerOfHanoi(n , source, destination, auxiliary):
if n==1:
print("Move disk 1 from source",source,"to destination",destination)
return
TowerOfHanoi(n-1, source, auxiliary, destination)
if n>0:
TowerOfHanoi(n,'A','B','C')
else:
print("Atleast give 1 disk")
Test Case1:
Provide input value for tower of hanoi problem3
Move disk 1 from source A to destination B
Move disk 2 from source A to destination C
Move disk 1 from source B to destination C
Move disk 3 from source A to destination B
Move disk 1 from source C to destination A
Move disk 2 from source C to destination B
Move disk 1 from source A to destination B
Test Case2:
Provide input value for tower of hanoi problem2
Move disk 1 from source A to destination C
Move disk 2 from source A to destination B
Move disk 1 from source C to destination B
1. For a given sequence of numbers having length>0 find the elements greater than 4 using lambda
and filter (built-in) functions.
TC1
Input:
0
Output:
No of Elements: 0
Atleast give 1 input
TC2
Input:
5
12
3
45
6
78
Output:
No of Elements: 5
Number of elements greater than 4 are: [12, 45, 6, 78]
TC3
Input:
-2
Output:
No of Elements: -2
Atleast give 1 input
Solution:
seq=[]
n=int(input("No of Elements: "))
print(n)
if n<=0:
print("Atleast give 1 input")
else:
for i in range(n):
no=int(input())
seq.append(no)
filtered_result = filter (lambda x: x > 4, seq)
print("Number of elements greater than 4 are:",list(filtered_result))
2.Write a recursive function which receives two arguments; M and b and checks whether M is the
prefect power of b, i.e, M=b**k, where k is a positive integer. Both M and b are non-zero positive
integers. The recursive function should return a number which is perfect power of b and less than or
equals to M if M is not a perfect power of b.
Test case 1:
Input:
625
5
Output:
625 is perfect power of 5
Test case 2:
Input:
243
3
Output:
243 is perfect power of 3
Test case 3:
Input:
72
4
Output:
72 is not a perfect power of 4
Nearest power is 64
Test case 4:
Input:
600
6
Output:
600 is not a perfect power of 6
Nearest power is 216
Code:
def if_power(N,d,t=True,p=0):
if N==1:
return t and True, d**p
elif N==d:
return t and True, d**(p+1)
elif N<d:
return t and False, d**p
elif N%d==0:
return if_power(N//d,d,t and True, p+1)
else:
return if_power(N//d,d,t and False, p+1)
N=int(input())
d=int(input())
Tv,n=if_power(N,d)
if Tv:
print('{} is perfect power of {}'.format(N,d))
else:
print('{} is not a perfect power of {}'.format(N,d))
print('Nearest power is {}'.format(n))
output
Enter first name: richa
Enter last name: sharma
Generated username: rchshrm
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
output
Enter a number: 5
The factorial of 5 is 120
5. Write a program to calculate GCD (Greatest Common Divisor) using Euclid’s Algorithm.
def gcd(a, b):
while b:
a, b = b, a % b
return a
output
Enter first number: 4
Enter second number: 12
The GCD of 4 and 12 is 4
else:
x=int(input("Provide "+str(i+1)+" th value"))
numbers.append(x)
output
1st
Provide total number of elements to be added into list3
Provide 1 st value1
Provide 2 nd value2
Provide 3 rd value3
Original numbers: [1, 2, 3]
Squared numbers: [1, 4, 9]
Sum of squared numbers: 14
2nd
Provide total number of elements to be added into list5
Provide 1 st value1
Provide 2 nd value3
Provide 3 rd value4
Provide 4 th value6
Provide 5 th value7
Original numbers: [1, 3, 4, 6, 7]
Squared numbers: [1, 9, 16, 36, 49]
Sum of squared numbers: 111
Output 2:
Provide integer input value for counter program7
Final count: 7
Output 3:
Provide integer input value for counter program7
Final count: 7
def counter():
count = 0
def increment():
nonlocal count
count += 1
def get_count():
return count
return increment, get_count
final_count = get_count_fn()
print("Final count:", final_count)
output 1:
Provide integer input value for counter program100
Final count: 100
Output 2:
Provide integer input value for counter program7
Final count: 7
Output 3:
Provide integer input value for counter program7
Final count: 7
2. Computer uses number for manipulation and storage in the different base number than
usual base 10. Use the concept of recursion to write a program for converting a given
decimal number (base 10) N into its equivalent hexadecimal number (base 16). 1
Test Case 1
Input:
Enter a base 10 number to convert into hexadecimal number:
8000
Output:
1F40
Test Case 2
Input:
Test Case3
Input:
Enter a base 10 number to convert into hexadecimal number:
150
Output:
96
Code:
def convert_digit_to_hex(x):
if x < 10:
return str(x)
elif (x == 10):
return 'A'
elif (x == 11):
return 'B'
elif (x == 12):
return 'C'
elif (x == 13):
return 'D'
elif (x == 14):
return 'E'
elif (x == 15):
return 'F'
def convert_number_to_hex(n):
remaining_digits = n // 16
last_digit = n % 16
if remaining_digits == 0:
return convert_digit_to_hex(last_digit)
else:
return convert_number_to_hex(remaining_digits) + convert_digit_to_hex(last_digit)
3. Pascal's triangle is widely used in combinatorics, probability theory and algebra. Generally, we
can use Pascals' triangle to find the probability of heads and tails in a toss, in combinations of cer -
tain things, etc. Now Rohit wants to use the specific row in his maths question. Write a python pro-
gram that takes input n and print nth row of pascal’s triangle.
Code:
x=int(input("Provide required integer input value"))
def p(n):
if n==1:
return [1]
else:
line = [1]
previous_line = p(n-1)
for i in range(len(previous_line)-1):
line.append(previous_line[i] +previous_line[i+1])
line += [1]
return line
print (p(x))
Test Case 1:
Provide required integer input value1
[1]
Test Case 2:
Provide required integer input value8
[1, 7, 21, 35, 35, 21, 7, 1]
4. Using lambda function to create custom sort order for a list of words
output 1:
Provide input list of strings being seperated by white spaces1 12 1 1234
Original words: ['1', '12', '1', '1234']
Words sorted by length and alphabetically: ['1', '1', '12', '1234']
Output 2:
Provide input list of strings being seperated by white spacesabcd
Original words: ['abcd']
Words sorted by length and alphabetically: ['abcd']
# Reducer function
def reducer(key, values):
return key, sum(values[1])+1
# Map phase
mapped_data = map(mapper, data)
# Reduce phase
total_length = reduce(reducer, mapped_data)[1]
output 1:
provide total number of elements in the input list3
Provide1th value10
Provide2th value20
Provide3th value100
Total Length: 101
Total Length: 10
Output 2:
provide total number of elements in the input list3
Provide1th value1
Provide2th value2
Provide3th value3
Total Length: 4
6. Python supports various types of arguments that can be passed at the time of the function call.
A default argument is a parameter that assumes a default value if a value is not provided in the
function call for that argument. Calculate perimeter of triangle by providing the input length a, b,
c. If b abd c are not passed to the function it takes the value 50 and 60 by default.
Code:
Test Case 1
Provide first parameter:10
Provide second parameter:20
Provide third parameter:30
When only a is passed:
a: 10
b: 50
c: 60
a+b+c: 120
When a and b are passed:
a: 10
b: 20
c: 60
a+b+c: 90
When a and b and c all are passed:
a: 10
b: 20
c: 30
a+b+c: 60
When a and b and c all are passed:
a: 40
b: 55
c: 65
a+b+c: 160
Test Case 2
Provide first parameter:10
Provide second parameter:0
Provide third parameter:-10
When only a is passed:
a: 10
b: 50
c: 60
a+b+c: 120
When a and b are passed:
a: 10
b: 0
c: 60
a+b+c: 70
When a and b and c all are passed:
a: 10
b: 0
c: -10
a+b+c: 0
Lab Programming – Version 3
Subject: Computational Programming & Thinking
Topic: Lambda Functions, Recursive Functions
Time-Duration: 2 hours
1.Computer uses the binary (base 2), octal (base 8), hexadecimal number system (base 16) instead
of decimal number system. Write a recursive function which will receive a decimal number (base
10) as argument and convert it to binary number (base 8).
Code:
def dec_bin(N,R=0,i=0):
if N<2:
return R+N*10**i
else:
r=N%2
N=N//2
R=R+r*10**i
return dec_bin(N,R,i+1)
print("Enter a decimal number: ")
N=int(input())
print("Bianry number: ")
print(dec_bin(N))
Test Case1:
Input:
Enter a decimal number:
7
Output:
Bianry number:
111
Test Case2:
Input:
Enter a decimal number:
2
Output:
Bianry number:
10
Test Case3:
Input:
Enter a decimal number:
8
Output:
Bianry number:
1000
Test Case4:
input:
Enter a decimal number:
100
Output:
Bianry number:
1100100
2. Suppose the Government has decided to take the Bank account number of a citizen and will
provide money equal to the sum of the didgits of the account number. You as an programmer given
the task to write a program to do the above task (that is find the sum of digits using recursive
function). Write a recursive Python program to complete the Government task.
Code:
print(sumDigits(n))
Test Case 1
Input:
Enter a number:
67876
Output:
34
Test Case 2
Input:
Enter a number:
6785453
Output:
38
Test Case 3:
Input:
Enter a number:
34323111
Output:
18
Test Case 4:
Input:
Enter a number:
11111111
Output:
8
3. Calculating Word Frequency using MapReduce
# Sample text
text = "This is a sample text for demonstrating MapReduce concept. MapReduce is a
popular programming model."
# Mapper function
def mapper(text):
words = text.split()
word_count = defaultdict(int)
for word in words:
word_count[word.lower()] += 1
return word_count.items()
# Reducer function
def reducer(word_count1, word_count2):
merged_word_count = defaultdict(int)
for word, count in word_count1:
merged_word_count[word] += count
for word, count in word_count2:
merged_word_count[word] += count
return merged_word_count.items()
# Map phase
mapped_data = map(mapper, [text])
# Reduce phase
word_count = reduce(reducer, mapped_data)
output
Word Frequency:
this: 1
is: 2
a: 2
sample: 1
text: 1
for: 1
demonstrating: 1
mapreduce: 2
concept.: 1
popular: 1
programming: 1
model.: 1
4. Complex numbers are the numbers that are expressed in the form of a+ib where, a,b are real
numbers and ‘i’ is an imaginary number called “iota”. The value of i = (√-1). For example, 2+3i is a
complex number, where 2 is a real number (Re) and 3i is an imaginary number (Im). An imaginary
number is usually represented by ‘i’ or ‘j’, which is equal to √-1. Therefore, the square of the
imaginary number gives a negative value. Finding the complex number with maximum absolute
value. Write a recursive function which will take a list of complex numbers as input and gives a
complex number with maximum absolute value. The absolute value of a complex number a+bj is
(a^2+b^2)^0.5.
Code:
def maxcomp(L,i=0):
if i==len(L)-1:
return L[i]
else:
m=L[i].real**2+L[i].imag**2
c=maxcomp(L,i+1)
if m>(c.real**2+c.imag**2):
return L[i]
else:
return c
L=eval(input())
print(maxcomp(L))
Test case 1:
Input:
[9+0j,1+3j,4-2j,0+1j,2+0j,-4-5j,3+1j, -10+2j, -20+8j]
Output:
(-20+8j)
Test case 2:
Input:
[9+0j,1+3j,4-2j,0+1j,2+0j,-4-5j,3+1j, -10+2j]
Output:
(-10+2j)
Test case 3:
Input:
[9+0j,1+3j,4-2j,0+1j,2+0j,-4-5j,3+1j]
Output:
(9+0j)
Test case 4:
Input:
[1+3j,4-2j,0+1j,2+0j,-4-5j,3+1j]
Output:
(-4-5j)
5. Filtering a list of strings to get only those starting with a specific letter using lambda
function
fruits = ["apple", "banana", "grape", "kiwi", "orange", "pear"]
soln
def calculator():
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
return x / y
if operation == '+':
result = add(num1, num2)
elif operation == '-':
result = subtract(num1, num2)
elif operation == '*':
result = multiply(num1, num2)
elif operation == '/':
result = divide(num1, num2)
else:
result = "Invalid operation"
return result
calculator_result = calculator()
print("Result:", calculator_result)
output
1.A list of numeric values is given containing both real and complex numbers. Sort the numbers
based on their absolute values. The absolute value of a complex number a+bj is (a^2+b^2)^0.5.
Also for negative real numbers only the absolute value is taken into consideration, i,e, between -5
and 2, -5 is greater. Use function to solve.
Test Cases:
Case 1:
Provide list of numbers as input in the form:[a,b,c...] where a,b,c etc can be real as well as
complex[1,2,3.5]
[1, 2, 3.5]
Case 2:
Provide list of numbers as input in the form:[a,b,c...] where a,b,c etc can be real as well as
complex[1+2j,3,-4]
[(1+2j), 3, -4]
Program:
def abs_value(C):
if type(C)==complex:
return (C.real**2+C.imag.real**2)**0.5
elif C<0:
return (-C)*(-C)
else:
return C*C
L=eval(input("Provide list of numbers as input in the form:[a,b,c...] where a,b,c etc can be real as
well as complex"))
L.sort(key=abs_value)
print(L)
2. A person has a list of words, where the words are written in small case letters. He wants to
convert each word of that list into uppercase letters. Write a python program (a recursive function)
that converts small case word list to uppercase words list. For Example ['delhi', 'panjab'] will be
input and output will be ['DELHI', 'PANJAB'].
Code:
def capitalizeWords(arr):
if len(arr) == 0:
return []
else:
return [arr[0].upper()]+capitalizeWords(arr[1:])
output 1:
Provide total numbers of elements3
Provide 1th input1
Provide 2th input2
Provide 3th input3
Original numbers: [1, 2, 3]
Even numbers: [2]
Output 2:
Provide total numbers of elements4
Provide 1th input2
Provide 2th input4
Provide 3th input8
Provide 4th input9
Original numbers: [2, 4, 8, 9]
Even numbers: [2, 4, 8]
output
5. There are N number cities with sequence number 1,2,3…N. There is network of roads between
the cities. If two cities are not connected directly by a road, they may have path through one or
more intermediate cities. For easier travel between the cities, a road-map is given in the form of a
nested list. The nested list contains elements such as L= [[(1,2),4], [(1,3),3]…[(1,1),1]….]. Each list
inside L is in the form of [(s,d), n], signifies the path is between source city s to destination d and in
order to move from s to d , the next intermediate city is n. An entry [(s,d),d] signifies a direct road
from s to d. An entry [(s,s),s] signifies, the source and destinations is the same city, so no need to
move to any next city. Write a recursive function which takes input the road-map in the form of a
nested list, sequence number of source city, sequence number of destination city and returns the
whole path from source to destination along with the intermediate nodes in the correct sequence.
Input (Input sequence L, s, d):
Code:
def findpath(L,s,d,P=[]):
e=(s,d)
j=0
P=P+[s]
if s==d:
return P
while j<len(L):
if L[j][0]==e:
break
j=j+1
if j==len(L):
return []
else:
return findpath(L,L[j][1],d,P)
L=eval(input("Provide input list mentioning various source and destination
pairs"))
s=int(input("Provide input number of source"))
d=int(input("Provide input number of destinaton"))
print(findpath(L,s,d))
Test case 1:
Provide input list mentioning various source and destination pairs[[(1,2),2],[(2,3),3],[(1,3),2]]
Provide input number of source1
Provide input number of desitinaton3
[1, 2, 3]
Test case 2:
Provide input list mentioning various source and destination pairs[(1,1),1]
Provide input number of source1
Provide input number of desitinaton1
[1]
6.Write a python program for subset sum problem. The input can be taken into an array or list. The
input can be positive or negative number. The sublist consists of contiguous elements to calculate
sum. Write a recursive function which will receive a list of numbers (L) and a sum (S) and displays
all such sublists of L which have S as the summation of all their elements. For an example
L=[2,5,4,7] and S=11, it should display solution exists (as [2,5,4] and [4,7] are two solutions). If no
sub-lists have addition of all its elements equals to S, then it should display, no solution exists.
Code:
def sub_sum(L,d,P=[],l=0):
sol=[]
if l==len(L):
for i in P:
if sum(i)==d:
sol.append(i)
return P,sol
elif l==0:
l=l+1
for i in range(len(L)):
P.append([L[i]])
return sub_sum(L,d,P,l)
else:
l=l+1
for p in P:
for i in range(len(L)):
if L[i] not in p:
L1=p+[L[i]]
L1.sort()
if L1 not in P:
P.append(L1)
return sub_sum(L,d,P,l)
print("Enter a list, for example [1,2,3,4] ")
L=eval(input())
print("Enter sum: ")
s=int(input())
L1,S=sub_sum(L,s)
if len(S)==0:
print('No Solution exists')
else:
print('Solution exists')
Test Case 1
Input:
Enter a list, for example [1,2,3,4]
[2,6,8,9]
Enter sum:
8
Output:
Solution exists
Test Case 2
Input:
Enter a list, for example [1,2,3,4]
[1,2,3,4]
Enter sum:
5
Output:
Solution exists
Test Case3
Input:
Enter a list, for example [1,2,3,4]
[2,4,5,7]
Enter sum:
10
Output:
No Solution exists
Test
Case 4
Input
Enter a list, for example [1,2,3,4]
[2,5,7,4]
Enter sum:
11
Output:
Solution exists
1.The students of Python class are asked to write a program to add 'ing' at the end of a given
string (length should be at least 3). If the given string already ends with 'ing' then add 'ly' in-
stead. If the string length of the given string is less than 3, leave it unchanged. Can you help
them to implement it?
Test Case 1 [Input must be a string]
Input
Interesting
Output
Interestingly
Test Case 2
Input
Interest
Output
Interesting
Test Case 3
Input
Go
Output
Go
Test Case 4
Input
Response
Output
Responseing
Test Case 5
Input
ping
Output
pingly
Program
def add_string(str1):
length = len(str1)
if length > 2:
if str1[-3:] == 'ing':
str1 += 'ly'
else:
str1 += 'ing'
return str1
print(add_string(input())
2.Once, Ram was playing a game with his brother. He asked him to extract all vowels present
in a given sentence. Can you help his brother to do it by a Python program?
Test Case 2
Input:
Listen class properly
Output
ie a oe
Test Case 3
Input:
Strengthen your foundations with the Python Programming Foundation
Output
ee ou ouaio i e o oai ouaio
Test Case 4
Input:
This is my string processing question set
Output
i i i oei ueio e
Program
a = ['a','e','i','o','u','A','E','I','O','U',' ']
b = input()
for i in b:
if i not in a:
b = b[:b.index(i)]+b[b.index(i)+1:]
print (b)
3.HItler’s junior brother Pitler is a Grammar nazi and he wants everything in order. He or-
dered you to write a program to check if the given input string’s characters are in alphabeti-
cal order or not.
Test Case 1
Input:
aabbccc
Output:
Yes
Test Case 2
Input:
aacba
Output:
No
Test Case 3
Input
bdst
Output
Yes
Test Case 4
Input
aaaaaaa
Output
Yes
Solution:
def isAlphabaticOrder(s):
n = len(s)
c = [s[i] for i in range(len(s))] # c=[“B”, “A”, “C”]
c.sort(reverse=False) # c=[“A”, “B”, “C”]
for i in range(n):
if c[i] != s[i]:
return False
return True
# Driver code
if __name__ == '__main__':
s = input("Enter a string to check: ") ABC
if isAlphabaticOrder(s):
print("Yes")
else:
print("No")
4. A set consists of elements: 18, 6, 40, 1, 25, 3, 10, 5, 55. Take an input from the user which is
present in the given set and remove it the set and then display the resultant set.
Input:
Original set elements: {18, 6, 40, 1, 25, 3, 10, 5, 55}
Enter the value you want to remove from the given set: 10
Output:
{18, 6, 40, 1, 25, 3, 5, 55}
Program:
Input:
Enter dictionary size: 3
Enter key: 1001
Enter value: Rohit
Enter key: 1002
Enter value: Ram
Enter key: 1003
Enter value: Raghav
Output:
1001 –> Rohit
1002 -> Ram
1003 -> Raghav
Program:
while i <= n:
key = int(input("Enter key: "))
value = input("Enter value: ")
dict[key] = value
i += 1
for k, v in dict.items():
print(k, '-', v)
6. Write a Python program calculate the product, multiplying all the numbers of a given tuple
Input
Enter the numbers seperated by space:12 12
output
Original Tuple:('12', '12')
Product - multiplying all the numbers of the said tuple: 144
Input
Enter the numbers seperated by space:12 7
Output
Output
Original Tuple:('12', '5', '8')
Product - multiplying all the numbers of the said tuple: 480
Program:
nums = tuple(input('Enter the numbers seperated by space:').split())
temp = (list(nums))
temp = [eval(i) for i in temp]
product = 1
for x in temp:
product *= x
print ("\nOriginal Tuple:{}".format(nums))
print("Product - multiplying all the numbers of the said tuple:{}".format(product))
7. Create a program that finds the average length of words in a sentence using an enumerator.
Program:
sentence = input()
words = sentence.split()
average_length = sum(len(word) for word in words) / len(words)
print("Average word length:", average_length)
Input:
This is a sample sentence to calculate average word length.
Output:
average word length: 5.0
Lab Programming8 – Version 1
Subject: Computational Programming & Thinking
Topic: Strings, Dictionary, Sets, Enum
Time-Duration: 2 hours
1.Create a program that finds the maximum value and its index in a list using an enumerator.
def find_max_with_index(numbers):
max_value = None
max_index = None
for index, value in enumerate(numbers):
if max_value is None or value > max_value:
max_value = value
max_index = index
return max_value, max_index
user_input = input("Enter a list of numbers separated by spaces: ")
numbers = [int(num) for num in user_input.split()]
value, index = find_max_with_index(numbers)
print(f"Maximum value is {value} at index {index}.")
o/p
Enter a list of numbers separated by spaces: 1 3 2 5 8 3
Maximum value is 8 at index 4.
4. Create a dictionary where the key hods the name of the countries and value indicates the
language most spoken in the corresponding country. Take first input as the no. of key value
pairs to be added in the dictionary. Write a program to print the content of this dictionary in
such a way that the key is sorted in the ascending order.
Code:
country_language = {}
for _ in range(num_pairs):
print(f"{key}: {country_language[key]}")
Input:
Output:
3
Input:
Rivers help in agriculture. In fact, a lot of farmers depend on rivers for agricultural purposes.
Output:
2
6. A user has to enter data in a web-portal for taxation. He has to enter his name and PAN
number. Write a program which will verify the entered data. The name must contain only al-
phabets and each word in the name must have its first letters as capital letters. The PAN num-
ber must contain alphanumeric values and must not contain any small letters.
Program:
name=input()
PAN=input()
name1=name.split()
t1=True
for i in name1:
t1=t1 and i.isalpha()
t=t1 and name.istitle() and PAN.isalnum() and (not PAN.isalpha()) and (not PAN.isdigit()) and PAN.
isupper()
print(t)
Input:
Rakesh Kumar Singh
PQWS123TR
Output:
True
Input:
Rakesh kumar Singh
PQWS123TR
Input:
Rakesh Kumar Singh12
PQWS123TR
Output:
False
Input:
Rakesh Kumar Singh
PQWSTR
Output:
False
Input:
Rakesh Kumar Singh
123STRQ34
Output:
True
Input:
Rakesh Kumar
PQWS123Tr
Output:
False
Input:
Rakesh Kumar
123456
Output:
False
Input:
Rakesh Kumar
PQW S123TR
Output:
False
Lab Programming8 – Version 2
Subject: Computational Programming & Thinking
Topic: Topic: Strings, Dictionary, Sets, Enum
Time-Duration: 2 hours
1. Create a dictionary by taking input from the user. Take first input as the no. of
key-value pairs and next inputs as the values of key-value pair. Check if it is empty
or not. If it is empty then display the message “ Empty” otherwise dispay the con-
tent of the dictionary.
Test Case 1:
Input:
Enter no. of key-value pairs: 3
Enter keys: 1
Enter values: 100
Enter keys: 2
Enter values: 200
Enter keys: 3
Enter values: 300
Output:
{1:100, 2:200, 3:300}
Test Case 2:
Input:
Enter no. of key-value pairs: 4
Enter keys: 3
Enter values: 300
Enter keys: 6
Enter values: 600
Enter keys: 7
Enter values: 700
Enter keys: 8
Enter values: 800
Output:
{3:300, 6:600, 7:700, 8:800}
Test Case 3:
Test Case 3”
Input:
Enter keys: 6
Enter values: 600
Enter keys: 9
Enter values: 900
Output:
{6:600, 9:900}
# Get the number of key-value pairs from the user
n = int(input("Enter no. of key-value pairs: "))
Program:
s1 = input("Enter the main string: ")
s2 = input("Enter the substring to search: ")
l1 = len(s1)
l2 = len(s2)
L = []
i=0
while i <= l1 - l2 + 1:
index = s1.find(s2, i, l1)
if index == -1:
break
i = index + 1
L.append(index)
print(L)
3. Lisa, a young tech enthusiast, always wondered where her emails were coming from. She
knew they came from servers, but she was curious about the names of these servers. One day,
after learning Python, she decided to write a program that extracts the server name from an
email address. Please help Lisa in writing the code.
Input:
[email protected]
Output:
gmail
Input:
[email protected]
Output:
yahoo
Input:
[email protected]
Output:
bennett
Program:
email=input()
i1=email.rfind('@')
i2=email.find('.',i1,len(email))
s=email[i1+1:i2]
print(s)
4. An English teacher gives a task to students that needs to be done in the following way: the
teacher gives a string as input then the students need to write the same string in such a way
that alphabets in half of the string are in lower case and remaining half (later half part) are in
upper case. Write a Python program to implement this.
Test Case 1 [Input must be a string]
Input
Bennett University
Output
Bennett UNIVERSITY
Test Case 2
Input
Bennett
Output
BenNETT
Test Case 3
Input
string processing
Output
string pROCESSING
Test Case 4
Input
Greater Noida (U.P)
Output
Greater NOIDA (U.P)
Program
def cap_half_string(str):
hlf_idx = len(str) // 2
res = ' '
for idx in range(len(str)):
# uppercasing later half
if idx >= hlf_idx:
res += str[idx].upper()
else :
res += str[idx]
print(res)
string = input()
cap_half_string(string)
5. In an attendance sheet, names of students are listed. Again, a duplicate attendance sheet is
created. The entries in duplicate attendance sheet is lesser than the original attendance sheet.
We must find the missing name in the duplicate attendance sheet to avoid any ambiguity.
Write a python program to solve the mentioned problem.
Input
Enter first set RAM SHYAM ROHIT
Enter second set RAM SHYAM
Output
The missing students are ['ROHIT']
Input
Enter first set hari rohan swati
Enter second set swati hari
Output
The missing students are ['rohan']
Input
Enter first set ram
Enter second set ram shyam rohit
Output
The missing students are ['rohit', 'shyam']
Program:
def lostElement(A,B):
A = set(A)
B = set(B)
6. Create a dictionary of student’s details by taking inputs from the user. First input is the no.
of students , second input is the key(Roll number) and the third input is the value( Name ).
The keys may not be in sorted order. Write a program to sort the given dictionary according
to the values of keys i.e keys should be arranged ascending order.
Input:
Enter no of students: 2
Enter a numeric key (Roll number) to insert in the dictionary: 25
Enter value( Name) for the target key: pinky
Enter a numeric key (Roll number) to insert in the dictionary: 1
Enter value( Name) for the target key: bhuvana
Output:
OrderedDict([(1,’bhuvana’), (25, ‘pinky’)])
Program:
from collections import OrderedDict
dict1 = OrderedDict(sorted(dict.items()))
print(dict1)
1. Create a dictionary by taking input from the user. Take first input as the no of key-
value pairs, next inputs as the corresponding key(string type) and value(integer
type). Write a program to find out the product of all elements of the dictionary.
Input:
Enter keys: a
Enter values:100
Enter keys: b
Enter values:200
Enter keys: c
Enter values:10
Output:
Product: 200000
Program:
i=1
dict1 = {}
while i <= n:
dict1[key1] = value1
i += 1
list1 = []
for i in dict1:
list1.append(dict1[i])
prod = 1
for j in list1:
prod *= j
2.Write a python program which takes two strings S1 and S2 as inputs and removes all the oc-
currences of S2 from S1, provided that S2 occurs at the end of a word in S1.
Input:
He played good cricket and could not edge the ball
ed
Output:
He play good cricket and could not edge the ball
Input:
if you are suffering from throat infection take ginger before singing
ing
Output:
if you are suffer from throat infection take ginger before sing
Program:
s1=input()
s2=input()
l=s1.split()
L=[i.strip() for i in l]
#print(L)
for i in range(len(L)):
if len(L[i])>=len(s2) and L[i][-len(s2):]==s2:
L[i]=L[i][:-len(s2)]
S=L[0]
for i in range(1,len(L)):
S=S+' '+L[i]
print(S)
3.Write a python program that receives to strings and calculates the number of words that
are same in both the strings
Input:
this is a apple
this is a dog
Output:
3
Input:
orange fruit contains more vitamin-c than apple fruit
kiwi fruit has three times more vitamin-c than orange fruit
Output:
6
Program:
s1=input()
s2=input()
d1=s1.split()
d2=s2.split()
D1=[i.strip() for i in d1]
D2=[i.strip() for i in d2]
c=0
for i in D1:
if i in D2:
c+=1
D2.remove(i)
print(c)
4. A Computer teacher teaches binary number system in his class. After the class, he gives
homework to students as the following question. Given a string as input, write a Python pro-
gram to check whether the given string is a binary string or not.
# driver code
if __name__ == "__main__" :
string = input()
check(string)
5.Write a Python program calculate the sum, by adding all the numbers of a given tuple.
Input:-
Enter the numbers separated by space:12 12 13
Output:-
Original Tuple:('12', '12', '13')
Sum - Adding all the numbers of the said tuple:37
Input:
Enter the numbers separated by space:12 -34 45
Output:-
Original Tuple:('12', '-34', '45')
Sum - Adding all the numbers of the said tuple:23
Input:-
Enter the numbers separated by space:12.56 23 44
Output:-
Original Tuple:('12.56', '23', '44')
Sum - Adding all the numbers of the said tuple:79.56
Program:
1.Two strings are given as input. Find the maximum length substring common to both the
strings. Implement using python program
Input:
assumptions
preassumption
Output:
assumption
Input:
The mistake was intentional
they take wastage
Output:
take was
Program:
s1 = input()
s2 = input()
l1 = len(s1)
l2 = len(s2)
if l1 < l2:
s1, s2 = s2, s1
l1, l2 = l2, l1
max_s = ''
max_l = 0
for i in range(l2):
for j in range(l2):
s = s2[i:j+1]
if s in s1 and len(s) > max_l:
max_s = s
max_l = len(s)
print(max_s)
2. A paragraph is stored as a string. The paragraph has to be formatted. Each line in the
paragraph should be near about N characters but must not have more than N characters. The
words should not be divided between the lines, i,e, a word must be in a single line. The value
of N is given as an input by the user.
80
Output:
Authorities in the Indian capital, Delhi, have shut all schools and colleges
indefinitely amid the worsening levels of air pollution. Construction work has
also been banned until 21 November but an exception has been made for transport
and defence-related projects. Only five of the 11 coal-based power plants in the
city have been allowed to operate. A toxic haze has smothered Delhi since the
festival of Diwali. The levels of PM2.5 tiny particles that can clog peoples
lungs in Delhi are far higher than the World Health Organizations (WHO) safety
guidelines. Several parts of the city recorded figures close to or higher than
400 on Tuesday, which is categorized as severe.
Input:
Authorities in the Indian capital, Delhi, have shut all schools and colleges indefinitely
amid the worsening levels of air pollution. Construction work has also been banned until
21 November but an exception has been made for transport and defence-related projects.
Only five of the 11 coal-based power plants in the city have been allowed to operate.
A toxic haze has smothered Delhi since the festival of Diwali. The levels of PM2.5
tiny particles that can clog peoples lungs in Delhi are far higher than the World Health
Organizations (WHO) safety guidelines. Several parts of the city recorded figures close
to or higher than 400 on Tuesday, which is categorized as severe.
100
Output:
Authorities in the Indian capital, Delhi, have shut all schools and colleges indefinitely amid the
worsening levels of air pollution. Construction work has also been banned until 21 November but
an
exception has been made for transport and defence-related projects. Only five of the 11 coal-based
power plants in the city have been allowed to operate. A toxic haze has smothered Delhi since the
festival of Diwali. The levels of PM2.5 tiny particles that can clog peoples lungs in Delhi are far
higher than the World Health Organizations (WHO) safety guidelines. Several parts of the city
recorded figures close to or higher than 400 on Tuesday, which is categorized as severe.
Program:
P = input()
N = int(input())
L = P.split()
l = ''
k = ''
for i in range(len(L)):
if i == 0:
k = L[i]
elif len(k) + len(L[i]) <= (N - 1):
k = k + ' ' + L[i]
else:
k = k + '\n'
l=l+k
k = L[i]
print(l)
3. You are developing data entry software. This form accepts a user name in First name,
Middle name and last name format. Develop a program which
A. Abbreviates the first and middle name except last name.
B. Your program should accept all the name formats like: first name, first
name+last name or first name+middle name +last name.
C. Convert the first letter in capital for each part of the name
Test Case 1 [Input must be a string consisting of less than 4 words]
Input:
ram Manohar Lohia
Output:
R.N. Lohia
Test Case 2
Input:
Rohan lal
Output:
R. Lal
Test Case 3
Input: asif
Output: Asif # do not abbreviate if only first name is given
Test Case 3
Input
bennett university Gnoida
Output
B. U. Gnoida
Solution:
a = input("enter string")
a = a.split()
if len(a)==1:
b=a[0][0].upper()+a[0][1:]
if len(a)==2:
b=a[0][0].upper()+"." +a[1]
if len(a)==3:
b = a[0][0].upper()+". "+a[1][0].upper()+". "+a[2][0].upper()+ a[2][1:]
print(b)
4. Create three dictionaries. For all the three dictionaries, give first input as the size of the
dictionary, second input as the key and third input as the value. Write a program to
concatenate the content of all these three dictionaries to create a fourth resultant dictionary.
5. Take different subjects of the current semester studied by the student as an input in a tuple
(each separated by comma). We have to find the number of subjects which has been input by
the student. In addition, in case if there is any repeated entry, only error message
”Error:The subjects entered are repeated” needs to be shown. If the subjects are unique,
Display the output pattern like what has shown in test cases.
Input1:-
Enter comma-separated subjects: english,hindi,science,social science
Output1:-
The subjects assigned in current semester are ('english', 'hindi', 'science', 'social science')
The number of assigned subjects are 4
Input2:-
Enter comma-separated subjects: science,hindi,social,hindi
Output2:-
Error:The subjects entered are repeated
Input3:-
Enter comma-separated subjects: python,maths,coi,dbms
Output3:-
The subjects assigned in current semester are: ('python', 'maths', 'coi', 'dbms')
The number of assigned subjects are: 4
Solution:-
cout = 0
my_tuple = tuple(input('Enter comma-separated subjects: ').split(','))
length = len(my_tuple)
for i in my_tuple:
if my_tuple.counnt(i) > 1:
cout = cout+1
if cout>0:
print('Error:The subjects entered are repeated')
else:
print('The subjects assigned in current semester are: {0}'.format(my_tuple))
print('The number of assigned subjects are: {}'.format(length))
6. Write a program that removes duplicate characters from a string using an enumerator.
def remove_duplicates(input_str):
seen = set()
result = []
for char in input_str:
if char not in seen:
seen.add(char)
result.append(char)
return ''.join(result)
input_string = input()
result = remove_duplicates(input_string)
print("String after removing duplicates:", result)
Input:
programming
Output:
String after removing duplicates: progamin
CSET101-2023-Lab09-Friday
1. Write a program that reads a list of integers and calculates their average. Handle any exceptions
that may occur.
Sol:
try:
numbers= [int(x) for x in input("Enter a list of integers:").split()]
average=sum(numbers)/len(numbers)
print("Average:", average)
except:
print("An error occurred while calculating the average")
2. Write a program that reads an integer from the user and prints its reciprocal. Handle the
ZeroDivisionError and ValueError exceptions.
Sol:
try:
num=int(input("Enter an integer:"))
reciprocal=1/num
print("Reciprocal:", reciprocal)
except ZeroDivisionError:
print("Error:Cannot divide by zero")
except ValueError:
print("Error: Inavlid input. Please enter a valid integer")
3. Write a program that prompts the user to enter some text and then saves that text to a file named "output.txt".
Sol:
try:
# Take user input for text
user_input = input("Enter some text: ")
# Open the file in write mode and write the user input to it
with open("output.txt", "w") as file:
file.write(user_input)
except Exception as e:
# Handle exceptions, if any
print(f"Error: {e}")
4. Write a Python program to demonstrate namespaces and variable scoping using local, global, and built-in
variables.
Sol:
# Global variable
global_variable = "I am global!"
def demonstrate_scoping(local_list):
# Local variable (list)
local_list.append("I am local!")
# Note: Since lists are mutable, changes inside the function affect the original list outside.
print("Outside function:", user_list)
5. Write a function that accepts a list of numbers and returns the sum of all even numbers. Handle the TypeError
exception.
Sol:
def sum_of_even_numbers(numbers):
try:
# Use a list comprehension to filter even numbers
even_numbers = [num for num in numbers if num % 2 == 0]
# Return the sum of even numbers
return sum(even_numbers)
except TypeError as e:
# Handle the TypeError exception
return f"Error: {e}"
# Example usage:
try:
# Take user input for a list of numbers
user_input = input("Enter a list of numbers separated by commas: ")
# Convert the input string to a list of integers
numbers_list = [int(num) for num in user_input.split(',')]
# Call the function and print the result
result = sum_of_even_numbers(numbers_list)
print(f"Sum of even numbers: {result}")
except ValueError:
print("Error: Please enter valid numbers.")
6. Write a Python program that reads multiple text files and concatenates their contents into a single text file
named "concatenated.txt".
Sol:
except FileNotFoundError:
print("File not found")
7. Create a Python program that reads a text file and counts the frequency of each word.
Sol:
def count_word_frequency(file_path):
try:
# Read the content of the text file
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
return word_frequency
except FileNotFoundError:
print(f"Error: File not found at path '{file_path}'")
return None
8. Create a program that calculates the area of a rectangle. Handle invalid input for length and width using
exception handling.
Sol:
1. Write a program that takes two numbers as input and calculates their division. Handle the ZeroDivisionError
exception.
Ans:
try:
# Perform division
except ZeroDivisionError:
except ValueError:
2. Write a program that reads integers from the user until a non-integer is entered. Handle the ValueError
exception.
Ans:
numbers=[ ]
while True:
try:
numbers.append(num)
except ValueError:
break
3. Write a program that reads the content of a text file named "sample.txt" and prints it to the console.
Ans:
try:
file_content = file.read()
print("File Content:")
print(file_content)
except FileNotFoundError:
except Exception as e:
print(f"An error occurred: {e}")
4. Write a Python program to create a module named "math_operations" that contains functions to add, subtract,
multiply, and divide two numbers
Ans:
# math_operations.py
"""Addition"""
return x + y
"""Subtraction"""
return x - y
"""Multiplication"""
return x * y
"""Division"""
if y != 0:
return x / y
else:
5. Create a Python program to demonstrate the concept of variable shadowing using local and global variables
with the same name.
Ans:
# Global variable
def demonstrate_shadowing():
demonstrate_shadowing()
shadow_variable = user_input
6. Write a Python program to demonstrate the scope resolution order of variables in a class hierarchy.
Ans:
variable_A = "A"
variable_B = "B"
variable_C = "C"
variable_D = "D"
def demonstrate_scope(local_A):
demonstrate_scope(user_input_A)
7. Create a Python program that generates Fibonacci series using a generator function and demonstrates the
use of local variables and namespaces.
Ans:
def generate_fibonacci(n):
fib_series = []
a, b = 0, 1
for _ in range(n):
fib_series.append(a)
a, b = b, a + b
return fib_series
def main():
result = generate_fibonacci(user_input)
if __name__ == "__main__":
main()
8. Write a Python program that reads the content of a text file and writes the reversed content to another file.
Ans:
try:
content = file.read()
reversed_content = content[::-1]
file.write(reversed_content)
# Open the output file in read mode and print its content
output_content = output_file_read.read()
print(output_content)
except FileNotFoundError:
except Exception as e:
def main():
if __name__ == "__main__":
main()
9. Write a program that converts temperature from Fahrenheit to Celsius. Handle the exception if the user enters
a non-numeric value.
Ans:
def fahrenheit_to_celsius(fahrenheit):
try:
return celsius
except ValueError:
def main():
try:
celsius = fahrenheit_to_celsius(fahrenheit)
except ValueError as e:
print(f"Error: {e}")
if __name__ == "__main__":
main()
CSET101-2023-Lab09-Thursday
1. Write a function that takes a dictionary as input and returns the value of a specified key. Handle the KeyError
exception.
Ans:
try:
value = dictionary[key]
return value
except KeyError:
return None
user_dict = {}
while True:
if key.lower() == 'done':
break
user_dict[key] = value
# Take user input for key
print("Result:", result)
2. Write a program that asks the user to enter their name and age. If the age is not a valid integer, raise a custom
AgeError.
Ans:
def get_user_info():
try:
age = int(age_str)
if age < 0:
print(f"Name: {name}")
print(f"Age: {age}")
except ValueError as e:
print(f"Error: {e}")
# Main program
get_user_info()
3. Write a program that reads a text file named "numbers.txt" containing integers separated by spaces. Calculate
and print the sum of those integers.
Sol:
try:
# Taking user input for the file name
file_name = input("Enter the file name: ")
except FileNotFoundError:
print(f"File '{file_name}' not found.")
except ValueError:
print("Invalid data in the file. Please ensure the file contains integers separated by spaces.")
4. Create a Python program that demonstrates the concept of built-in namespaces by using built-in functions like
"len()", "sum()", and "max()".
Sol:
# Function to calculate the average of a list
def calculate_average(numbers):
return sum(numbers) / len(numbers)
try:
# Taking user input for a list of numbers
numbers = [float(x) for x in input("Enter a list of numbers separated by space: ").split()]
except ValueError:
print("Please enter valid numerical values.")
Sol:
main.py
# Import my_module with an alias
import my_module as mm
my_module.py
def greet(name):
return f"Hello, {name}!"
6. Write a function that accepts a list of numbers and returns the sum of all even numbers. Handle the TypeError
exception.
Sol:
def sum_of_even_numbers(numbers):
try:
# Use a list comprehension to filter even numbers
even_numbers = [num for num in numbers if num % 2 == 0]
# Return the sum of even numbers
return sum(even_numbers)
except TypeError as e:
# Handle the TypeError exception
return f"Error: {e}"
# Example usage:
try:
# Take user input for a list of numbers
user_input = input("Enter a list of numbers separated by commas: ")
# Convert the input string to a list of integers
numbers_list = [int(num) for num in user_input.split(',')]
# Call the function and print the result
result = sum_of_even_numbers(numbers_list)
print(f"Sum of even numbers: {result}")
except ValueError:
print("Error: Please enter valid numbers.")
7. Write a Python program that reads the contents of a text file and adds line numbers at the beginning of each
line. Write the modified content into another file.
Sol:
def add_line_numbers(input_path, output_path):
try:
with open(input_path, 'r') as input_file:
lines = input_file.readlines()
except FileNotFoundError:
print("File not found")
# Example Usage
input_file_path = input("Enter the input file path: ")
output_file_path = input("Enter the output file path: ")
add_line_numbers(input_file_path, output_file_path)
8. Write a program that merges the contents of multiple text files into a single file.
Sol:
def merge_files(file_names, output_name):
file_not_found = False
try:
with open(output_name, 'w') as output_file:
for file_name in file_names:
try:
with open(file_name, 'r') as file:
content = file.read()
output_file.write(content)
except FileNotFoundError:
file_not_found = True
print(f"FILE NOT FOUND: {file_name}")
except FileNotFoundError:
print("File not found")
9.Develop a program that maintains a contact information system. Users can add contacts with names and phone
numbers. Handle exceptions for duplicate entries and ensure that the user is notified if a contact already exists.
Sol:
contacts = {}
def add_contact():
name = input("Enter name: ")
phone = input("Enter phone number: ")
try:
if name in contacts:
raise ValueError("Contact already exists!")
else:
contacts[name] = phone
print(f"Contact added: {name} - {phone}")
except ValueError as e:
print(f"Error: {e}")
def display_contacts():
print("Contacts:")
for name, phone in contacts.items():
print(f"{name}: {phone}")
# Example Usage
while True:
print("1. Add Contact\n2. Display Contacts\n3. Exit")
choice = input("Enter your choice (1/2/3): ")
if choice == '1':
add_contact()
elif choice == '2':
display_contacts()
elif choice == '3':
print("Exiting...")
break
else:
print("Invalid choice. Please enter 1, 2, or 3.")
CSET101-2023-Lab09-Tuesday
1. Write a program that opens a file called "data.txt" and reads its content. Handle the FileNotFoundError
exception.
Ans:
def read_file(file_name):
try:
content = file.read()
print("File content:")
print(content)
except FileNotFoundError:
except Exception as e:
def main():
read_file(file_name)
if __name__ == "__main__":
main()
2. Write a function that accepts a list of numbers and returns the sum of all even numbers. Handle the TypeError
exception.
Ans.
def sum_of_even_numbers(numbers):
try:
return sum(even_numbers)
except TypeError as e:
# Example usage:
try:
result = sum_of_even_numbers(numbers_list)
except ValueError:
3. Write a program that prompts the user to enter some text and then saves that text to a file
named "output.txt".
Ans:
try:
# Open the file in write mode and write the user input to it
file.write(user_input)
file_content = file.read()
print("Content in 'output.txt':")
print(file_content)
except Exception as e:
print(f"Error: {e}")
Ans:
import my_module as mm
# Use the alias to call the function from the module with user input
result = mm.greet(user_name)
print(result)
5. Create a Python program that demonstrates the use of built-in namespaces by overriding a built-
in function temporarily.
Ans:
def override_len(s):
global len
original_len = len
result = len(s)
len = original_len
result = len(s)
original_len = len
# User input
override_len(user_input)
6. Write a Python program to read a text file named "text.txt" and count the occurrences of each
word. Display the word frequency in descending order.
Ans:
def count_word_frequency(file_path):
try:
content = file.read()
# Tokenize the words and count their occurrences
words = content.split()
word_counts = Counter(words)
print(f'{word}: {count}')
except FileNotFoundError:
count_word_frequency(file_path)
7. Create a Python program that reads a text file, encrypts its content using a simple substitution
cipher, and writes the encrypted text to another file.
Ans:
result = ""
if char.isalpha():
if char.isupper():
else:
result += char
return result
def encrypt_file():
try:
shift = 3
content = file.read()
file.write(encrypted_content)
print(content)
encrypted_text = file.read()
print(encrypted_text)
except Exception as e:
encrypt_file()
8. Create a program that simulates a user login. Ask the user to enter a username and password.
Handle the exception if the username is not found or if the password is incorrect.
Ans:
user_credentials = {
"john_doe": "password123",
"alice_smith": "secure_pass",
"bob_jackson": "letmein",
def simulate_login():
try:
if username in user_credentials:
if password == user_credentials[username]:
print("Login successful!")
else:
else:
except Exception as e:
simulate_login()
CSET101-2023-Lab09-Wednesday
1. Write a program that prompts the user to enter their age. If the age is not a positive integer, raise a ValueError.
Sol:
try:
if age <= 0:
except ValueError as e:
print("Error:", e)
2. Write a program that reads a number from the user and calculates its square root. Handle the ValueError and
MathError exceptions.
Sol:
import math
try:
num=float(input("Enter a number:"))
if num<0:
raise ValueError("Number must be non-negative.")
result= math.sqrt(num)
print("Square root:", result)
except ValueError as e:
print("Error:",e)
3. Write a program that opens a file called "data.txt" and reads its content. Handle the FileNotFoundError
exception.
Sol:
def read_file(file_name):
try:
# Open the file in read mode
with open(file_name, 'r') as file:
# Read and print the content
content = file.read()
print("File content:")
print(content)
except FileNotFoundError:
print(f"Error: The file '{file_name}' was not found.")
except Exception as e:
print(f"An error occurred: {e}")
def main():
# Take user input for the file name
file_name = input("Enter the file name: ")
if __name__ == "__main__":
main()
4. Write a Python program to demonstrate namespaces and variable scoping using local, global, and built-in
variables.
Sol:
# Global variable
global_variable = ""
def outer_function():
# Local variable in outer_function
outer_variable = input("Enter a value for outer_variable: ")
def inner_function():
# Local variable in inner_function
inner_variable = input("Enter a value for inner_variable: ")
inner_function()
outer_function()
5. Create a Python program to demonstrate importing only specific functions from a module using the "from"
keyword. Consider the value of a and b as 5 and 3.
Sol:
main.py
# User input to select the operation
operation = input("Enter operation (add/subtract/multiply/divide): ")
6. Write a Python program that demonstrates the difference between local and global variables in a nested
function scenario.
Sol:
# Global variable
global_variable = ""
def outer_function():
# Local variable in outer_function
outer_variable = input("Enter a value for outer_variable: ")
def inner_function():
# Local variable in inner_function
inner_variable = input("Enter a value for inner_variable: ")
inner_function()
outer_function()
7. Create a program that reads a text file and finds the longest line in terms of characters.
Sol:
def find_longest_line(file_path):
try:
with open(file_path, 'r') as file:
lines = file.readlines()
if not lines:
print("The file is empty.")
return
except FileNotFoundError:
print(f"File not found at path: {file_path}")
except Exception as e:
print(f"An error occurred: {str(e)}")
# Example usage
find_longest_line(filename)
8. Design a simple banking application that allows users to deposit and withdraw money from their accounts.
Handle exceptions for insufficient balance during withdrawals.
Sol:
balance = 0
def deposit():
global balance
amount = float(input("Enter the deposit amount: "))
if amount > 0:
balance += amount
print(f"Deposit successful. Current balance: {balance}")
else:
print("Invalid deposit amount. Please deposit a positive amount.")
def withdraw():
global balance
amount = float(input("Enter the withdrawal amount: "))
if amount > 0:
if amount <= balance:
balance -= amount
print(f"Withdrawal successful. Current balance: {balance}")
else:
print("Insufficient balance. Withdrawal failed.")
else:
print("Invalid withdrawal amount. Please withdraw a positive amount.")
def check_balance():
print(f"Current balance: {balance}")
# Example Usage
if __name__ == "__main__":
deposit()
check_balance()
withdraw()
check_balance()