22csp03 PP Lab QB
22csp03 PP Lab QB
22csp03 PP Lab QB
1.A. Rajesh runs a small business and wants to calculate the profit percentage he
made on a particular sale. He needs a program that takes the cost price (cp), the
rate of appreciation (ra), and the selling price (sp) as input, and calculates the profit
percentage. Help Rajesh by writing a program that takes the cost price, rate of
appreciation, and selling price, and computes the profit percentage.
PROGRAM:
cp = int(input())
ra = int(input())
sp = int(input())
cp += ra
sp -= cp
print("{:.2f}".format(sp*100/cp))
INPUT
4700
800
5800
OUTPUT
5.45
1.
1.B. Write a program that solves the following problem:
You have a square and a rectangle
1. The side of the square is of length 10 cm. Assign this value to the
variables.
2. The sides of the rectangle have length 25cm and breadth 17cm.
3. Assign these values to the variables l and b respectively
4. The cost of painting the square is Rs. 4 per cm^2.
calculate the cost of painting a square with a given side length at a
specified cost per square cm.
PROGRAM:
s = 17
areas = s*s
l = 19
b = 18
arear = l*b
areadiff = arear - areas
costs = areas * 4
print("The area of Square is", areas )
print("The area of Rectangle is", arear )
print("The difference of areas is", areadiff)
print("Cost of painting the Square is", costs)
OUTPUT:
The area of Square is 289
The area of Rectangle is 342
The difference of areas is 53
Cost of painting the Square is 1156
1.C. We have the variable a = 0b10111011.Use a bitmask and the value
a in order to achieve a result where all of the bits in a are flipped. Be
sure to print your answer as a bin() string.
PROGRAM:
a = 0b10111011
bitmask = int('1' * len(bin(a)[2:]), 2)
flipped_a = a ^ bitmask
print("Flipped a:", bin(flipped_a))
OUTPUT:
Flipped a: 0b10111100
2. Programs for demonstrating control statements
PROGRAM:
side1 = float(input())
side2 = float(input())
side3 = float(input())
triangle_type = ""
if side1 == side2 and side2 == side3:
triangle_type = "Equilateral"
if side1 == side2 and side2 != side3 or side1 != side2 and side2 == side3
or side1 == side3 and side2 != side3:
triangle_type = "Isosceles"
if side1 != side2 and side2 != side3 and side1 != side3:
triangle_type = "Scalene"
print(f"The triangle is classified as {triangle_type}")
INPUT
90.0
90.0
90.0
OUTPUT
The triangle is classified as Equilateral
2.B. Write a Python program that takes a person's age as input and
determines their life stage based on the following criteria:
"Child" if the age is 12 or below.
"Teen" if the age is between 13 and 19 (inclusive).
"Adult" if the age is 20 or above
Input Format:
A single integer value representing the person's age.
Output Format:
A single string that says either "Child", "Teen", or "Adult".
PROGRAM:
age = int(input("Enter the age: "))
if age <= 12:
print("Child")
elif age <= 19:
print( "Teen")
else:
print( "Adult")
INPUT:
Enter the age:13
OUTPUT:
Teen
2.C. Write a Python program that reads an integer N from the user and
then reads N integers. The program should calculate the product of all
positive numbers and the sum of all negative numbers from the provided
integers. Finally, it should output these two results.
Input Format:
The first line contains an integer N (1 ≤ N ≤ 100), the number of integers to
follow.
The next N lines each contain one integer ai(-1000 ≤ ai≤ 1000).
Output Format:
The first line should contain the product of the positive numbers.
The second line should contain the sum of the negative numbers.
PROGRAM:
N = int(input("Enter the number of integers: "))
positive_product = 1
negative_sum = 0
has_positive = False
for i in range(N):
number = int(input())
if number > 0:
positive_product *= number
has_positive = True
elif number < 0:
negative_sum += number
if has_positive:
print("Product of positive numbers:", positive_product)
else:
print("Product of positive numbers: 0")
print("Sum of negative numbers:",negative_sum)
INPUT:
Enter the number of integers: 5
3
-2
4
-1
0
OUTPUT:
Product of positive numbers: 12
Sum of negative numbers: -3
3. Programs to implement various string operations.
AIM:
To write a Python program that modifies a given string by adding 'ing' at the end if its length
is atleast 3.If the string already ends with'ing', add'ly' instead.If the string length is less than 3, leave it
unchanged.
ALGORITHM:
STEP 1: Start
STEP 2: Define a function add_string that takes one parameter str1, which is the input string.
STEP 3: Get the length of the input string using len(str1) and store it in the variable length.
STEP 4: Check if the length of the string is greater than 2.
STEP 5: If the length is greater than 2:
a. Check if the last three characters of the string (str1[-
3:]) are equal to 'ing'.
b. If they are, append 'ly' to the string (str1 += 'ly').
c. If not, append 'ing' to the string (str1 += 'ing').
AIM:
To Write a Python program to get a string madeof the first2 and last 2 characters of a given
string.If the string length is less than 2,return the empty string instead.
ALGORITHM:
STEP 1: Start.
STEP 2: Function Definition: The string_both_ends function takes a single parameter, str,
which is the input string.
STEP 3: Check Length: It first checks if the length of the input string is less than 2 (if
len(str) < 2).
If it is, the function returns an empty string ''
STEP 4: Concatenation: If the length of the input string is greater than or equal to 2, the
function returns a string Containing the first two characters of the input string (str[0:2])
concatenated with the last two characters of the input string (str[-2:]).
STEP 5: Return: The resulting concatenated string is returned.
STEP 6: Test Cases: The function is tested with three different input strings using the print
statements.
STEP 7: End.
PROGRAM:
def string_both_ends(str):
iflen(str) < 2:
return ''
returnstr[0:2] + str[-2:]
print(string_both_ends('w3resource'))
print(string_both_ends('w3'))
print(string_both_ends('w'))
OUTPUT:
w3ce
w3w3
3.C. PROBLEM STATEMENT:
Write a Python program to remove unwanted characters from a given
string.
Original String :Pyth*^on Exercis^es
After removing unwanted characters: Python Exercises
Original String : A%^!B#*CD
After removing unwanted characters: ABCD
AIM:
To write a Python program that removes unwanted characters from a given string,
leaving only alphanumeric characters.
ALGORITHM:
STEP 1: Start
STEP 2: Input: Take the original string str1 and a list of unwanted characters
unwanted_chars.
STEP 3: Initialize an empty string: Create an empty string result to store the modified string.
STEP 4: Iterate through each character in the original string: Loop through each character in
str1.
STEP 5: Check if the character is unwanted: For each character, check if it exists in the list
unwanted_chars.
STEP 6: Append to result if not unwanted: If the character is not in unwanted_chars, append
it to the result string.
STEP 7: Return the result: Once all characters have been processed, return the modified
string result.
STEP 8: End
PROGRAM:
def remove_chars(str1,unwanted_chars):for i in unwanted_chars:
str1=str1.replace(i,'')return str1
str1="Pyth*^onExercis^es"str2= "A%^!B#*CD"
unwanted_chars=["#","*","!","^","%"]
print("OriginalString:"+str1)
print("Afterremovingunwantedcharacters:")
print(remove_chars(str1,unwanted_chars))
print("\nOriginalString:"+str2)
print("Afterremovingunwantedcharacters:")
print(remove_chars(str2,unwanted_chars))
OUTPUT:
OriginalString:Pyth*^on Exercis^es After
removing unwanted characters:
PythonExercises
OriginalString:A%^!B#*CD
Afterremovingunwantedcharacters:
ABCD
4. Programs for demonstrating the following
i. Lists
ii. Tuples
iii. Dictionaries
i. Lists
4.1.1. Problem Statement
Write a Python program to find common elements that takes two lists as input and
returns a new list containing the common elements between the two input lists.
Input Format
The first line consists of space-separated integers representing the elements of the
first list.
The second line consists of space-separated integers representing the elements of
the second list.
Output Format
The output prints the common elements between the given two lists.
If there are no common elements, the output prints the empty list.
Write a Python program that takes a sentence as input and returns a new sentence
with the words reversed.
Write a Python program to sort a list according to the length of the elements.
ii. Tuple
Gowshik is working on a task that involves taking two lists of integers as input,
finding the element-wise sum of the corresponding elements, and then creating a
tuple containing the sum values.
Given tuples:
(1, 2, 3, 4)
(3, 5, 2, 1)
4.2.2.Problem Statement
4.2.3.Problem Statement
Given a list of numbers of list, write a Python program to create a list of tuples
having the first element as the number and the second element as the cube of the
number.
Input Format
The first line of input consists of an integer, representing the size of the list N.
The following N lines of input consist of the integers, representing the elements of
the list.
Output Format
The output displays the list of tuples with a cube of each number in the input list.
iii. Dictionary
Write a Python program that takes an integer n as input and then takes n key-value
pairs as input to populate a dictionary my_dict. Each key is a string, and the
corresponding value is an integer.
The program should then find and print the three highest values in the dictionary in
descending order.
4.3.2. Problem Statement
Write a Python program to sort a dictionary based on its values in ascending order.
Input Format
The first line contains the keys of the given dictionary as space-separated elements.
The second line contains the values of the given dictionary as space-separated
elements.
Output Format
The output displays the given dictionary in ascending order in separate lines in the
format: "[key] : [value]".
Ram did grocery shopping. He has a list of items along with the quantity he bought
and price of each item. Can you please help him to find the total amount he spent.
Create a list of dictionaries with each dictionary has item name, quantity and price.
For example,
[
{ "product": "Milk", "quantity": 1.5, "price": 10.5},
{ "product": "Eggs", "quantity": 12.0, "price": 0.25}
]
Pass this dictionary to the function and get the total sum of the amount Ram spent
in grocery shop. Round the output to 2 decimal places.
5. Programs to demonstrate concepts using functions
Input Format
The first line of the input consists of an integer that represents the height.
The second line of the input consists of an integer which represents the
radius.
Output Format
The output prints the volume of the cone rounding off to two decimal
places.
PROGRAM
import math
def cone_volume(h, r):
return round((1/3)*math.pi*(r**2)*h,2)
m=int(input())
n=int(input())
print(cone_volume(m, n))
Input
2
8
Output
134.04
Output Format
The output displays the maximum of the three numbers a, b, and c.
Program
def max_of_two( x, y ):
if x > y:
return x
return y
def max_of_three(a,b,c):
return max_of_two( a, max_of_two(b,c))
a = int(input())
b = int(input())
c = int(input())
print(max_of_three(a,b,c))
Input:
10
50
-100
Output
50
You are given a non-negative integer n. Your task is to calculate the sum of
powers of 2 from 0 to n (inclusive) using math module.
def findSum(n):
s=0
for i in range(0, n + 1):
s += math.pow(2, i)
return s
n = int(input())
print(findSum(n))
Input
8
Output
511.0
Program
def line_count():
file = open("story.txt","r")
count=0
for line in file:
if line[0] not in 'T':
count+= 1
file.close()
print("No of lines not starting with 'T'=",count)
line_count()
Program
def display_words():
file = open("poem.txt","r")
data = file.read()
words = data.split()
for word in words:
if len(word) < 4:
print(word, end=" ")
file.close()
display_words()
count_words()
Input Format
The first line of the input consists of an integer that represents the height.
The second line of the input consists of an integer which represents the radius.
Output Format
The output prints the volume of the cone rounding off to two decimal places.
Refer to the sample output for the formatting specifications.
Constraints
1 <= height, radius <= 100
Test CaseInputOutput
2134.04
8
Weightage – 20InputOutput
123216.99
16
Weightage – 25InputOutput
34282024.96
89
Weightage – 30InputOutput
1114110.99
35
Weightage – 25Sample InputSample Output
5256.56
7
Solution
import math
defcone_volume(h, r):
return round((1/3)*math.pi*(r**2)*h,2)
m=int(input())
n=int(input())
print(cone_volume(m, n))
Input Format
The input will be a single line containing the password to be checked.
Output Format
The program will output one of the following messages:
If the given password is strong, the program will print "The password is strong"
Otherwise, it will print "The password is not strong"
Constraints
The password can contain any printable ASCII characters.
The length of the password should be at most 100 characters.
Output:
Solution
import re
defis_strong_password(password):
# Check if the password has at least eight characters
iflen(password) < 8:
return False
return True
def main():
password = input()
ifis_strong_password(password):
print("The password is strong")
else:
print("The password is not strong")
if __name__ == "__main__":
main()
7.3) Write a Python function that takes a text, an old word, and a new word
as input, and replaces all occurrences of the old word with the new word in
the text.
Input Format
The first line consists of the strings as a text in which you need to find and replace the old word.
The second line consists of the string that needs to be replaced.
The third line consists of the string to replace.
Output Format
The output prints the updated text after replacing all occurrences of the old word with the new
word.
Output:
Solution
import re
defreplace_word(text, old_word, new_word):
pattern = r'\b' + re.escape(old_word) + r'\b'
updated_text = re.sub(pattern, new_word, text)
returnupdated_text
input_text = input()
old_word = input()
new_word = input()
8.1) Write a function that takes a piece of text as input and extracts all the
integers (whole numbers) from the given text.
The function should use regular expressions to identify and extract the integers correctly.
Input Format
The input consists of a string containing alphanumeric characters, special characters, and spaces,
and may include integers in various formats.
Output Format
The output prints a list of strings representing the extracted integers from the input text.
Output:
Output :
import re
ip = input()
print(re.sub(r'\\e', 'e', ip))
8.3) Write a Python program so that for the given input list, it filters all
elements that contain the number 42 surrounded by word characters using
regular expression.
Note:
import re
Input Format
The first input is the N value which is an integer.
The next input is the list of strings as per the value of N.
Output Format
The output is a list of string which has characters in and around 42
Output :
Solution
import re
words=[]
n=int(input())
for i in range(n):
words.append(input())
print([w for w in words if re.search(r'\B42\B', w)])
PROBLEM STATEMENT:
Write a Python GUI program to design a paint application using Tkinter where the user can draw
on the Canvas widget with different colors
AIM:
To write a Python GUI program using the tkinter module that creates an paint application
using Tkinter where the user can draw on the Canvas widget with different colors.
ALGORITHM:
Step 1: Start
Step 3: Define global variables to track the drawing state (drawing), last coordinates (last_x, last_y),
and pen color (pen_color).
Step 4: start_drawing: Sets drawing to True and initializes last_x and last_y
Step 5: stop_drawing: Sets drawing to False when the drawing action is stopped
Step 7: Define a function change_color to update the pen_color based on the button clicked
Step 8: Create a Canvas widget where drawing will happen, set its dimensions and background color.
Step 9: Create buttons for different pen colors using a list of predefined colors.
Step 10: Each button is associated with the change_color function using lambda to pass the color as
an argument.
Step 11: Bind mouse events (<Button-1>, <ButtonRelease-1>, <B1-Motion>) to the canvas and
associate them with the corresponding event handler functions (start_drawing, stop_drawing, draw)
Step 12: Finally, start the main event loop using root.mainloop() to display the GUI and handle user
interactions.
Step 13:Stop
PROGRAM:
import tkinter as tk
drawing = False
def start_drawing(event):
global drawing
drawing = True
def stop_drawing(event):
global drawing
drawing = False
def draw(event):
if drawing:
x, y = event.x, event.y
last_x, last_y = x, y
def change_color(new_color):
global pen_color
pen_color = new_color
root = tk.Tk()
root.title("Paint Application")
canvas = tk.Canvas(root, width=400, height=300, bg="white")
canvas.pack()
color_buttons = []
color_buttons[-1].pack(side=tk.LEFT)
canvas.bind("<Button-1>", start_drawing)
canvas.bind("<ButtonRelease-1>", stop_drawing)
canvas.bind("<B1-Motion>", draw)
root.mainloop()
Output:
RESULT:
Thus the python programming for GUI has been Executed and verified successfully
[[ 2 3 4]
[ 5 6 7]
[ 8 9 10]]
AIM:
To write a NumPy program that creates a 3x3 matrix with values ranging from 2 to 10.
ALGORITHM:
STEP 1: Start
STEP 2: Import NumPy: Import the NumPy library to use its functionalities.
- Use np.arange() function to generate an array of numbers from start to stop with the specified step.
STEP 7: End
PROGRAM:
importnumpy as np
x = np.arange(2, 11).reshape(3, 3)
print(x)
OUTPUT:
[[ 2 3 4]
[ 5 6 7]
[ 8 9 10]]
RESULT:
Thus the python programming for Numpy module has been Executed and verified successfully.
10.2. PROBLEM STATEMENT:
Write a NumPy program to append values to the end of an array.
Expected Output:
Original array:
[10 20 30 40 50 60 70 80 90]
AIM:
ALGORITHM:
STEP 1: Start
STEP 2: Import NumPy: Import the NumPy library to use its functionalities.
STEP 3: Initialize an Array: Create an initial NumPy array with some values.
STEP 4: Define Values to Append: Decide on the values you want to append to the array.
- Specify the array to which you want to append (array) and the values (values_to_append).
- Store the result in a new array variable or update the original array if needed.
STEP 6: Output the Updated Array: Print or display the array after appending the values.
PROGRAM:
importnumpy as np
print("Original array:")
print(x) x = np.append(x, [[40, 50, 60], [70, 80, 90]])
print(x)
OUTPUT:
Original array:
[10 20 30 40 50 60 70 80 90]
RESULT:
Thus the python programming for Numpy module has been Executed and verifiedsuccessfully.
Array1: [ 0 10 20 40 60]
[10 40]
AIM:
ALGORITHM:
STEP 1: Start
STEP 2: Import NumPy: Import the NumPy library to use its functionalities.
STEP 3: Initialize Arrays: Create two NumPy arrays with some values.
- Use NumPy'snp.intersect1d() function to find the intersection of elements between the two arrays.
- Store the result in a new array variable to hold the common values.
STEP 5: Output the Common Values: Print or display the array containing the common values.
PROGRAM:
importnumpy as np
print(np.intersect1d(array1, array2))
OUTPUT:
Array1: [ 0 10 20 40 60]
[10 40]
RESULT:
Thus the python programming for Numpy module has been Executed and verified
successfully.