0% found this document useful (0 votes)
5 views34 pages

parcticalpython[11]

Uploaded by

sidaksingh269
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
5 views34 pages

parcticalpython[11]

Uploaded by

sidaksingh269
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 34

Problem Solving using Python Programming (23CS001)

Practical File
Of
Problem Solving using
Python Programming
24CSE0101
Submitted

in partial fulfillment for the award of the degree

of

BACHELEOR OF ENGINEERING
in

COMPUTER SCIENCE & ENGINEERING

CHITKARA UNIVERSITY

CHANDIGARH-PATIALA NATIONAL HIGHWAY


RAJPURA (PATIALA) PUNJAB-140401 (INDIA)

December, 2024

Submitted To: Submitted By:

Dr.lekha rani Sidak Singh


Associate Professor 2410991536
Chitkara University, Punjab 1st Sem, 2024

Problem Solving using Python Programming (24CS0101) Page 1


Problem Solving using Python Programming (23CS001)

List of Practicals
Sr. Practical Name Page Teacher
No Number Signature
1. a) Write a Python Program to Calculate the Area of a 5,6
Triangle
b) Write a Python Program to Swap Two Variables
c) Write a Python Program to Convert Celsius to 7,8
Fahrenheit
2. a.) Write a Python Program to Check if a Number is Odd or 9,10
Even
b.) Write a Python Program to Check if a Number is
Positive, Negative or 0
c.) Write a Python Program to Check Armstrong Number 11,12
3. a.) Write a Python program to check if a given number is 13,14
Fibonacci number?
b.) Write a Python program to print cube sum of first n
natural numbers.
c.) Write a Python program to print all odd numbers in a 15,16
range.
4. a.) Write a Python Program to Print Pascal Triangle 17,18
Hint: Enter number of rows: 4
1
1 1
1 2 1
1 3 3 1
b.) WAP to Draw the following Pattern for n number:
11111
2222
333
44
5
5. Write a program with a function that accepts a string from 19,20
keyboard and create a new string after converting
character of each word capitalized. For instance, if the
sentence is “stop and smell the roses” the output should
be “Stop And Smell The Roses”
6. a.) Write a program that accepts a list from user. Your 19,20
program should reverse the content of list and display it.
Do not use reverse () method.
b) Find and display the largest number of a list without 21,22
using built-in function
max (). Your program should ask the user to input values in
list from keyboard.
Problem Solving using Python Programming (23CS001) Page 2
Problem Solving using Python Programming (23CS001)

7. Find the sum of each row of matrix of size m x n. For 21,22


example, for the following matrix output will be like this:

Sum of row 1 = 32
Sum of row 2 = 31
Sum of row 3 = 63
8. a) Write a program that reads a string from keyboard and 23,24
display:
* The number of uppercase letters in the string.
* The number of lowercase letters in the string.
* The number of digits in the string.
* The number of whitespace characters in the string.
b) Python Program to Find Common Characters in Two
Strings.
c) Python Program to Count the Number of Vowels in a 25,26
String.

9. a) Write a Python program to check if a specified element 27,28


presents in a tuple of
tuples.
Original list:
((‘Red’ ,’White’ , ‘Blue’),(‘Green’, ’Pink’ , ‘Purple’),
(‘Orange’, ‘Yellow’, ‘Lime’))
Check if White present in said tuple of tuples!
True
Check if Olive present in said tuple of tuples!
False
b) Write a Python program to remove an empty tuple(s)
from a list of tuples.
Sample data: [(), (), ('',), ('a', 'b'), ('a', 'b', 'c'), ('d')]
Expected output: [('',), ('a', 'b'), ('a', 'b', 'c'), 'd']
10. a) Write a Program in Python to Find the Differences 29,30
Between Two Lists Using Sets.
11. a) Write a Python program Remove duplicate values 29,30
across Dictionary Values.
Input : test_dict = {‘Manjeet’: [1], ‘Akash’: [1, 8, 9]}
Output : {‘Manjeet’: [], ‘Akash’: [8, 9]}
Input : test_dict = {‘Manjeet’: [1, 1, 1], ‘Akash’: [1,
1, 1]}
Output : {‘Manjeet’: [], ‘Akash’: []}

Problem Solving using Python Programming (23CS001) Page 3


Problem Solving using Python Programming (23CS001)

b) Write a Python program to Count the frequencies in a 31,32


list using dictionary in Python.
Input : [1, 1, 1, 5, 5, 3, 1, 3, 3, 1,4, 4, 4, 2, 2, 2, 2]
Output :
1:5
2:4
3:3
4:3
5:2
Explanation : Here 1 occurs 5 times, 2 occurs 4
times and so on...
12. a) Write a Python Program to Capitalize First Letter of 31,32
Each Word in a File.

b.) Write a Python Program to Print the Contents of File in 33,34


Reverse Order.
13. WAP 33,34
to catch an exception and handle it using try and except cod
e blocks.
14. Write a Python Program to Append, Delete and Display 35,36
Elements of a List using Classes.
15. Write a Python Program to Find the Area and Perimeter of 37,38
the Circle using Class.
16. Create an interactive application using Python's Tkinter
library for graphics programming.

Problem Solving using Python Programming (23CS001) Page 4


Problem Solving using Python Programming (23CS001)

Program 1: a) Write a Python Program to Calculate the


Area of a Triangle

base = 10
height = 5
result = 0.5*base*height
print("Area of the triangle:", result)

Output 1: a)

Program 1. b) Write a Python Program to Swap Two


Variables

a=5
b = 10
a, b = b, a
print(“Swapped variables:”, a,b)

Output 1: b)

Problem Solving using Python Programming (24CS0101) Page 5


Problem Solving using Python Programming (23CS001)

Program 1. c) Write a Python Program to Convert


Celsius to Fahrenheit

celsius = 30
fahrenheit = (celsius * 9/5) + 32
print("Temperature in Fahrenheit:", fahrenheit)

Output 1: c)

Program 2: a)Write a Python Program to check if a


number is odd or even
def check_odd_even(num):
if num % 2 == 0:
print(num, "is even")
else:
print(num, "is odd")
check_odd_even(10)
check_odd_even(11)
Output 2: a)

10 is even
11 is odd

Problem Solving using Python Programming (23CS001) Page 6


Problem Solving using Python Programming (23CS001)

Program 2. b) Write a Python Program to Check if a


Number is Positive, Negative or 0
def check_number(num):
if num > 0:
return "Positive"
elif num < 0:
return "Negative"
else:
return "Zero"
number = -5
result = check_number(number)
print("The number is:", result)

Output 2: b)

Program 2: c) Program to check if a number is an


Armstrong number
def is_armstrong(number):

digits = str(number)

num_digits = len(digits)

sum_of_powers = sum(int(digit) ** num_digits for digit in digits)

return sum_of_powers == number

if is_armstrong(153):

print(f"{number} is an Armstrong number.")

else:

print(f"{number} is not an Armstrong number.")

Output 2: c)
Problem Solving using Python Programming (23CS001) Page 7
Problem Solving using Python Programming (23CS001)

153 is an Armstrong number.

Problem Solving using Python Programming (23CS001) Page 8


Problem Solving using Python Programming (23CS001)

Program 3. a) Write a Python program to check if a given


number is a Fibonacci number.
# Program to check if a number is Fibonacci
def is_fibonacci(n):
a, b = 0, 1
while a < n:
a, b = b, a + b
return a == n

# Example usage
num = 5
result = is_fibonacci(num)
print("Is Fibonacci number?", result)

Program 3: b) Write a Python program to print the cube


sum of the first n natural numbers.
# Program to calculate the cube sum of first n natural numbers
def cube_sum(n):
return sum(i**3 for i in range(1, n + 1))

# Example usage
n=3
result = cube_sum(n)
print("Cube sum of first", n, "natural numbers:", result)
Output 3: a)

Problem Solving using Python Programming (23CS001) Page 9


Problem Solving using Python Programming (23CS001)

Output 3: b)

Program 3: c) Write a Python program to print all odd


numbers in a range.
# Program to print all odd numbers in a range

def print_odd_numbers(start, end):

return [num for num in range(start, end + 1) if num % 2 != 0]

# Example usage

start = 1

end = 10

result = print_odd_numbers(start, end)

print("Odd numbers in the range:", result)

Output 3: c)

Problem Solving using Python Programming (23CS001) Page 10


Problem Solving using Python Programming (23CS001)

Problem 4. a) Write a Python Program to Print Pascal's


Triangle
# Program to print Pascal's Triangle
def pascal_triangle(n):
triangle = []
for i in range(n):
row = [1] * (i + 1)
for j in range(1, i):
row[j] = triangle[i - 1][j - 1] + triangle[i - 1][j]
triangle.append(row)
return triangle

# Example usage
n = int(input(“Enter number of rows:”))
result = pascal_triangle(n)
for row in result:
print(row)

Program 4. b) Write a Python Program to Draw the


Following Pattern
# Program to draw a specific pattern
def draw_pattern(n):
for i in range(1, n + 1):
print((str(i) + ' ') * (n - i + 1))

# Example usage
n = int(input('Enter n: '))
draw_pattern(n)

Problem Solving using Python Programming (23CS001) Page 11


Problem Solving using Python Programming (23CS001)

Output 4: a)

Output 4: b)

Problem Solving using Python Programming (23CS001) Page 12


Problem Solving using Python Programming (23CS001)

Program 5. Write a program with a function that accepts


a string from keyboard and creates a new string after
capitalizing each word.
# Program to capitalize each word in a string
def capitalize_words(sentence):
return ' '.join(word.capitalize() for word in sentence.split())
# Example usage
input_string = input(“Enter the string: ”)
result = capitalize_words(input_string)
print("Capitalized string:", result)

Program 6. a) Write a program that accepts a list from


the user, reverses the content of the list, and displays it.
Do not use the reverse() method.
# Program to reverse a list without using reverse()
def reverse_list(lst):
return lst[::-1]

# Example usage
user_input = input("Enter numbers separated by spaces: ")
input_list = list(map(int, user_input.split()))
reversed_list = reverse_list(input_list)
print("Reversed list:", reversed_list)

Problem Solving using Python Programming (23CS001) Page 13


Problem Solving using Python Programming (23CS001)

Output 5:

Output 6: a)

Problem Solving using Python Programming (23CS001) Page 14


Problem Solving using Python Programming (23CS001)

Program 6. b) Find and display the largest number of a


list without using the built-in function max().
# Program to find the largest number in a list without using max()
def find_largest(lst):
largest = lst[0]
for num in lst:
if num > largest:
largest = num
return largest

# Example usage
user_input = input("Enter numbers separated by spaces: ")
input_list = list(map(int, user_input.split()))
largest_number = find_largest(input_list)
print("Largest number:", largest_number)

Problem 7. Find the sum of each row of a matrix of size m


x n.
# Program to find the sum of each row of a matrix

def sum_of_rows(matrix):
return [sum(row) for row in matrix]

# Example usage
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
row_sums = sum_of_rows(matrix)
print("Sum of each row:", row_sums)

Problem Solving using Python Programming (23CS001) Page 15


Problem Solving using Python Programming (23CS001)

Output 6: b)

Output 7:

Problem Solving using Python Programming (23CS001) Page 16


Problem Solving using Python Programming (23CS001)

Problem 8. a) Write a program that reads a string from


keyboard and displays the number of uppercase letters,
lowercase letters, digits, and whitespace characters.
# Program to count different character types in a string
def count_character_types(string):
uppercase = sum(1 for c in string if c.isupper())
lowercase = sum(1 for c in string if c.islower())
digits = sum(1 for c in string if c.isdigit())
whitespace = sum(1 for c in string if c.isspace())
return uppercase, lowercase, digits, whitespace

# Example usage
input_string = input("Enter a string: ")
result = count_character_types(input_string)
print("Uppercase letters:", result[0])
print("Lowercase letters:", result[1])
print("Digits:", result[2])
print("Whitespace characters:", result[3])

Problem 8. b) Write a Python Program to Find Common


Characters in Two Strings.
# Program to find common characters in two strings
def common_characters(str1, str2):
return set(str1) & set(str2)

# Example usage
string1 = "hello"
string2 = "world"
result = common_characters(string1, string2)
print("Common characters:", result)

Problem Solving using Python Programming (23CS001) Page 17


Problem Solving using Python Programming (23CS001)

Output 8: a)

Output 8: b)

Problem Solving using Python Programming (23CS001) Page 18


Problem Solving using Python Programming (23CS001)

Problem 8. c) Write a Python Program to Count the


Number of Vowels in a String.
# Program to count the number of vowels in a string
def count_vowels(string):
vowels = "aeiouAEIOU"
return sum(1 for char in string if char in vowels)

# Example usage
input_string = "Hello World"
result = count_vowels(input_string)
print("Number of vowels:", result)

Problem Solving using Python Programming (23CS001) Page 19


Problem Solving using Python Programming (23CS001)

Output 8: c)

Problem Solving using Python Programming (23CS001) Page 20


Problem Solving using Python Programming (23CS001)

Problem 9: a) Write a Python program to check if a


specified element is present in a tuple of tuples.
# Program to check if an element is in a tuple of tuples
def check_in_tuples(tuples, element):
for tup in tuples:
if element in tup:
return True
return False

# Example usage
tuple_of_tuples = (('Red', 'White', 'Blue'), ('Green', 'Pink', 'Purple'), ('Orange', 'Yellow',
'Lime'))
result = check_in_tuples(tuple_of_tuples, "White")
print("Is the element present?", result)

Problem 9. b) Write a Python program to remove empty


tuple(s) from a list of tuples.
# Program to remove empty tuples from a list
def remove_empty_tuples(tuple_list):
#In Python, empty tuples () are considered False in a boolean context, while non
#empty tuples are True.
return [tup for tup in tuple_list if tup]

# Example usage
list_of_tuples = [(), (), ('',), ('a', 'b'), ('a', 'b', 'c'), ('d')]
result = remove_empty_tuples(list_of_tuples)
print("List after removing empty tuples:", result)

Problem Solving using Python Programming (23CS001) Page 21


Problem Solving using Python Programming (23CS001)

Output 9: a)

Output 9: b)

Problem Solving using Python Programming (23CS001) Page 22


Problem Solving using Python Programming (23CS001)

Problem 10. a) Write a Program in Python to Find the


Differences Between Two Lists Using Sets.
# Program to find differences between two lists using sets
def list_differences(list1, list2):
return list(set(list1) - set(list2)), list(set(list2) - set(list1))
# Example usage
list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
diff1, diff2 = list_differences(list1, list2)
print("Difference in list1:", diff1)
print("Difference in list2:", diff2)

Problem 11. a) Write a Python program to remove


duplicate values across Dictionary Values.
# Program to remove duplicate values across dictionary values
def remove_duplicates(dict_values):
seen = set()
result = {}
for key, values in dict_values.items():
result[key] = []
for value in values:
if value not in seen:
seen.add(value)
result[key].append(value)
return result

# Example usage
sample_dict = {‘Manjeet’: [1, 1, 1], ‘Akash’: [1, 1, 1]}
result = remove_duplicates(sample_dict)
print("Dictionary after removing duplicates:", result)

Problem Solving using Python Programming (23CS001) Page 23


Problem Solving using Python Programming (23CS001)

Output 10:

Output 11: a)

Problem Solving using Python Programming (23CS001) Page 24


Problem Solving using Python Programming (23CS001)

11. b) Write a Python program to count the frequencies in


a list using a dictionary.
def count_frequencies(lst):
frequency_dict = {}
for item in lst:
# Check if the item is already in the dictionary
if item in frequency_dict:
frequency_dict[item] += 1
else:
frequency_dict[item] = 1
return frequency_dict

# Example usage
input_list = [1, 1, 1, 5, 5, 3, 1, 3, 3, 1,4, 4, 4, 2, 2, 2, 2]
result = count_frequencies(input_list)
print("Frequencies:", result)

Problem 12. a) Write a Python Program to Capitalize the


First Letter of Each Word in a File.
# Program to capitalize the first letter of each word in a file
def capitalize_file_words(file_path):
with open(file_path, 'r') as file:
content = file.read()
capitalized_content = ' '.join(word.capitalize() for word in content.split())
return capitalized_content

# Example usage
# Assuming 'input.txt' contains the text
file_path = 'input.txt'
result = capitalize_file_words(file_path)
print("Capitalized content:", result)

Problem Solving using Python Programming (23CS001) Page 25


Problem Solving using Python Programming (23CS001)

Output 11: b)

Output 12(depends on content of 'input.txt'): a)

Problem Solving using Python Programming (23CS001) Page 26


Problem Solving using Python Programming (23CS001)

Problem 12. b) Write a Python Program to Print the


Contents of a File in Reverse Order.
# Program to print the contents of a file in reverse order
def print_file_reverse(file_path):
with open(file_path, 'r') as file:
content = file.readlines()
for line in reversed(content):
print(line.strip())

# Example usage
# Assuming 'input.txt' contains multiple lines
file_path = 'input.txt'
print_file_reverse(file_path)

Problem 13. Write a program to catch an exception and


handle it using try and except code blocks.
# Program to demonstrate exception handling
def divide_numbers(a, b):
try:
result = a / b
except ZeroDivisionError:
return "Cannot divide by zero."
return result

# Example usage
num1 = 10
num2 = 0
result = divide_numbers(num1, num2)
print("Result:", result)

Problem Solving using Python Programming (23CS001) Page 27


Problem Solving using Python Programming (23CS001)

Output 12(depends on content of 'input.txt'): b)

Output 13:

Problem Solving using Python Programming (23CS001) Page 28


Problem Solving using Python Programming (23CS001)

14. Write a Python Program to Append, Delete and


Display Elements of a List using Classes.
# Program to append, delete and display elements of a list using classes
class ListManager:
def __init__(self):
self.elements = []

def append_element(self, element):


self.elements.append(element)

def delete_element(self, element):


if element in self.elements:
self.elements.remove(element)
else:
return "Element not found."

def display_elements(self):
return self.elements

# Example usage
manager = ListManager()
manager.append_element(1)
manager.append_element(2)
manager.delete_element(1)
print("Current list:", manager.display_elements())

Problem Solving using Python Programming (23CS001) Page 29


Problem Solving using Python Programming (23CS001)

Output 14:

Problem Solving using Python Programming (23CS001) Page 30


Problem Solving using Python Programming (23CS001)

Problem 15: Write a Python Program to Find the Area


and Perimeter of the Circle using Class.
# Program to find the area and perimeter of a circle using a class
import math

class Circle:
def __init__(self, radius):
self.radius = radius

def area(self):
return math.pi * (self.radius ** 2)

def perimeter(self):
return 2 * math.pi * self.radius

# Example usage
circle = Circle(5)
print("Area of the circle:", circle.area())
print("Perimeter of the circle:", circle.perimeter())

Problem Solving using Python Programming (23CS001) Page 31


Problem Solving using Python Programming (23CS001)

Output 15:

Problem Solving using Python Programming (23CS001) Page 32


Problem Solving using Python Programming (23CS001)

Problem 16: Create an interactive application using Python's


Tkinter library for graphics programming.
import tkinter as tk

class CounterApp:
def __init__(self, root):
self.root = root
self.root.title("Simple Counter App")

# Initialize the counter value


self.counter = 0

# Label to display the counter


self.counter_label = tk.Label(root, text="0", font=("Arial", 48))
self.counter_label.pack(pady=20)

# Increase button
self.increase_button = tk.Button(root, text="Increase", command=self.increase, font=("Arial", 14))
self.increase_button.pack(side=tk.LEFT, padx=20)

# Decrease button
self.decrease_button = tk.Button(root, text="Decrease", command=self.decrease, font=("Arial", 14))
self.decrease_button.pack(side=tk.LEFT, padx=20)

# Reset button
self.reset_button = tk.Button(root, text="Reset", command=self.reset, font=("Arial", 14))
self.reset_button.pack(side=tk.LEFT, padx=20)

def increase(self):
self.counter += 1
self.update_counter()

def decrease(self):
self.counter -= 1
self.update_counter()

def reset(self):
self.counter = 0
self.update_counter()

def update_counter(self):
self.counter_label.config(text=str(self.counter))

# Create the Tkinter window and run the application


root = tk.Tk()
app = CounterApp(root)
root.mainloop()

Problem Solving using Python Programming (23CS001) Page 33


Problem Solving using Python Programming (23CS001)

Output 16:

Problem Solving using Python Programming (23CS001) Page 34

You might also like