1.
a) Write a python script to perform different Arithmetic Operations on numeric data types
in Python (CO1).
b)Develop a program to replace a specific word or phrase in a text file with another word
or phrase. CO2
a)
a = float(input(“Enter a number a:”))
b = float(input(“Enter a number b:”))
print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)
print("Floor Division:", a // b)
print("Modulus:", a % b)
print("Exponentiation:", a ** b)
b)
filename = “F:\SJIT\python\[Link]”
oldword = input(“Enter the word/phrase to be replaced: “)
newword = input(“Enter the new word/phrase: “)
with open(filename,”r”) as f:
data = [Link]()
newdata = [Link](old_word, new_word)
with open(filename, “w”) as f:
[Link](newdata)
print(“Replacement completed successfully.”)
2. a) Write a program to display Pascal’s triangle.
b)Create a program to encrypt and decrypt a text file using a simple substitution cipher
technique. CO2
a)
n = int(input(“Enter no of rows:”))
for i in range(n):
num = 1
for j in range(i + 1):
print(num, end=" ")
num = num * (i - j) // (j + 1)
print()
b)
plain = "abcdefghijklmnopqrstuvwxyz"
cipher = "qwertyuiopasdfghjklzxcvbnm"
def encrypt(text):
return ''.join(
(cipher[[Link]([Link]())].upper() if [Link]()
else cipher[[Link](ch)]) if [Link]() in plain else ch
for ch in text
def decrypt(text):
return ''.join(
(plain[[Link]([Link]())].upper() if [Link]()
else plain[[Link](ch)]) if [Link]() in cipher else ch
for ch in text
data = open("sales_2.txt").read()
open("[Link]", "w").write(encrypt(data))
print("Encrypted")
data = open("[Link]").read()
open("[Link]", "w").write(decrypt(data))
print("Decrypted")
3. a )Write a python program that uses a while loop to add up all the even numbers between
100 and 200.
b )Create a program to extract all words containing a specific substring from a text
document. CO2
a) i = 100
s=0
while i <= 200:
if i % 2 == 0:
s += i
i += 1
print(s)
b)
substring = input()
with open("[Link]", "r") as f:
text = [Link]()
words = [Link]()
result = []
for w in words:
if substring in w:
[Link](w)
with open("[Link]", "w") as f:
[Link](" ".join(result))
4. a )Write a python Program to Demonstrate a Function with and without Arguments (CO1)
b )Write a Python program that utilizes regular expressions to extract all email addresses
from a given text document. CO2
a)
def without_args():
print("Function without arguments")
def with_args(a, b):
print(a + b)
without_args()
with_args(5, 10)
b)
import re
with open("[Link]", "r") as f:
text = [Link]()
emails = [Link](r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}', text)
with open("[Link]", "w") as f:
[Link]("\n".join(emails))
5. a )Demonstrate how functions return multiple values with an example.
b )Implement a program to extract all phone numbers (including various formats) from a
string using regular expressions. CO2
a)
def values(a, b):
return a + b, a - b, a * b
x, y, z = values(10, 5)
print(x, y, z)
b)
import re
# open and read the file
file = open(“[Link]”, “r”)
text = [Link]()
pattern = r’(\+91[-\s]?)?[6-9]\d{9}|\(?\d{3,5}\)?[-\s]?\d{3,5}[-\s]?\d{4}’
matches = [Link](pattern, text)
print(“Phone Numbers Found:”)
for match in matches:
print([Link]())
6. a )Implement a program to count the occurrences of each character in the given
string.CO1.
b) Create a class called library with data attributes like acc_number, publisher, title and author. The
methods of the class should include
a. read() – acc_number, title, author.
b. compute() - to accept the number of days late, calculate and display the
finecharged at the rate of $1.50 per day.
c. display the data. CO2
a)
s = input("Enter a string: ")
freq = {}
for ch in s:
if ch in freq:
freq[ch] += 1
else:
freq[ch] = 1
for k, v in [Link]():
print(k, v)
b)
class Library:
def read(self):
self.acc_number = input("Enter Accession Number: ")
[Link] = input("Enter Title: ")
[Link] = input("Enter Author: ")
[Link] = input("Enter Publisher: ")
def compute(self):
days = int(input("Enter number of days late: "))
fine = days * 1.50
print("Fine to be paid: $", fine)
def display(self):
print("\nLibrary Book Details")
print("Accession Number:", self.acc_number)
print("Title:", [Link])
print("Author:", [Link])
print("Publisher:", [Link])
b1 = Library()
[Link]()
[Link]()
[Link]()
7. a ) Develop a program to check if a given string, is a palindrome.CO1
b )Define a Car class with attributes such as make, model, and color, along with methods for
displaying information and changing attributes. CO3
a)
s = input("Enter a string to check if it is palindrome or not: ")
i, j = 0, len(s) - 1
is_palindrome = True
while i < j:
if s[i] != s[j]:
is_palindrome = False
break
i += 1
j -= 1
if is_palindrome:
print("The Given String is Palindrome")
else:
print("The Given String is Not a Palindrome")
b)
class Car:
def __init__(self, make, model, color):
[Link] = make
[Link] = model
[Link] = color
def display(self):
print("Make :", [Link])
print("Model:", [Link])
print("Color:", [Link])
def update(self, make=None, model=None, color=None):
if make:
[Link] = make
if model:
[Link] = model
if color:
[Link] = color
c1 = Car("Honda", "City", "White")
print("Original Details:")
[Link]()
[Link](color="Black", model="Amaze")
print("\nUpdated Details:")
[Link]()
8. a )Write a program to search for a substring within a given string and print its index. CO1
b )Create a Vehicle base class with common attributes and methods, and then derive Car and
Motorcycle classes inheriting from it. CO3
a)
s = input("Enter A String: ")
s1 = input("Enter a Substring: ")
# Use the find() method to locate the starting index
index = [Link](s1)
# Print the result
print("Substring found at index", index)
b)
class Vehicle:
def __init__(self, brand, speed):
[Link] = brand
[Link] = speed
def display(self):
print("Brand:", [Link])
print("Speed:", [Link])
class Car(Vehicle):
def __init__(self, brand, speed, doors):
super().__init__(brand, speed)
[Link] = doors
def show_car(self):
[Link]()
print("Doors:", [Link])
class Motorcycle(Vehicle):
def __init__(self, brand, speed, type):
super().__init__(brand, speed)
[Link] = type
def show_bike(self):
[Link]()
print("Type:", [Link])
c1 = Car("Toyota", 180, 4)
m1 = Motorcycle("Yamaha", 150, "Sport")
print("Car Details:")
c1.show_car()
print("\nMotorcycle Details:")
m1.show_bike()
9.a )Implement a program to find all occurrences of a specific pattern within a string. CO1
b )Write a program to add two polynomials using classes CO3
a)
s = input("Enter main string: ")
pattern = input("Enter pattern to search: ")
positions = []
for i in range(len(s) - len(pattern) + 1):
if s[i:i+len(pattern)] == pattern:
[Link](i)
print("Positions:")
for p in positions:
print(p)
b)
class Polynomial:
def __init__(self, coeffs):
[Link] = coeffs # list of coefficients
def add(self, p):
result = []
length = max(len([Link]), len([Link]))
for i in range(length):
a = [Link][i] if i < len([Link]) else 0
b = [Link][i] if i < len([Link]) else 0
[Link](a + b)
return Polynomial(result)
def display(self):
for i, c in enumerate([Link]):
if c != 0:
print(f"{c}x^{i}", end=" + ")
print("0")
p1 = Polynomial([5, 2, 3]) # 5 + 2x + 3x²
p2 = Polynomial([1, 4, 2]) # 1 + 4x + 2x²
print("Polynomial 1:")
[Link]()
print("Polynomial 2:")
[Link]()
p3 = [Link](p2)
print("Sum of Polynomials:")
[Link]()
10. a )Write a python program to create, append, and remove elements in lists in Python.
b )Implement a Shape base class with common attributes and methods, and then create
subclasses like Rectangle, Circle, and Triangle. CO3
a)
lst = [10,20,30,40]
print(“List is:”,lst)
[Link](50)
print(lst)
[Link](20)
print(lst)
b)
class Shape:
def area(self):
print("Area not defined for generic shape")
class Rectangle(Shape):
def __init__(self, length, width):
[Link] = length
[Link] = width
def area(self):
print("Rectangle Area:", [Link] * [Link])
class Circle(Shape):
def __init__(self, radius):
[Link] = radius
def area(self):
print("Circle Area:", 3.14 * [Link] * [Link])
class Triangle(Shape):
def __init__(self, base, height):
[Link] = base
[Link] = height
def area(self):
print("Triangle Area:", 0.5 * [Link] * [Link])
r = Rectangle(5, 4)
c = Circle(3)
t = Triangle(6, 2)
[Link]()
[Link]()
[Link]()
11. a )Write a program that creates a list of numbers 1–100 that are either divisible by 5 or 6
b)Define a class called student. Display the marks details of top five students using inheritance. CO3
a)
lst = []
for i in range(1, 101):
if i % 5 == 0 or i % 6 == 0:
[Link](i)
print(lst)
b)
class Student:
def __init__(self,name,marks):
[Link]=name
[Link]=marks
class Top5(Student):
def display(self,students):
print("Top 5 students marks:")
top_students = sorted(students, key=lambda s: [Link], reverse=True)[:5]
for s in top_students:
print("Name:", [Link], "Marks:", [Link]
s1 = Student("Ravi", 95)
s2 = Student("Sita", 92)
s3 = Student("Arjun", 90)
s4 = Student("Priya", 88)
s5 = Student("Kiran", 85)
s6 = Student("Charan",100)
students=[s1,s2,s3,s4,s5,s6]
top = Top5("",0)
[Link](students)
12. a )Write a python program to demonstrate working with dictionaries in Python. (CO1)
b )Utilize polymorphism to create a function that takes objects of different subclasses and
calls their common methods. CO3
a)
d = {}
n = int(input("Enter number of key-value pairs: "))
for i in range(n):
k = input("Enter key: ")
v = input("Enter value: ")
d[k] = v
d[input("Enter key to add: ")] = input("Enter value: ")
del d[input("Enter key to delete: ")]
for k, v in [Link]():
print(k, v)
b)
class Dog:
def sound(self):
print("Bark")
class Cat:
def sound(self):
print("Meow")
class Cow:
def sound(self):
print("Moo")
def make_sound(obj):
[Link]()
d = Dog()
c = Cat()
co = Cow()
make_sound(d)
make_sound(c)
make_sound(co)
13. a )Write a program that has the dictionary of your friends’ names as keys and phone
numbers as its values. Print the dictionary in a sorted order. Prompt the user to enter the
name and check if it is present in the dictionary. If the name is not present, then enter the
details in the dictionary(CO1)
b)Write a python program to calculate the sum of every column in a NumPy array (CO4)
a)
d = {}
n = int(input("Enter number of contacts: "))
for i in range(n):
name = input("Enter your name: ")
phone = input("Enter your phone number: ")
d[name] = phone
print("\nContact List:")
for k in sorted(d):
print(k, d[k])
search = input("\nEnter name to search: ")
if search in d:
print("Phone number:", d[search])
else:
print("Contact not found. Add new contact.")
new_phone = input("Enter phone number: ")
d[search] = new_phone
print("\nUpdated Contact List:")
for k in sorted(d):
print(k, d[k])
b)
import numpy as np
r = int(input("Enter number of rows: "))
c = int(input("Enter number of columns: "))
arr = []
for i in range(r):
row = list(map(int, input().split()))
[Link](row)
a = [Link](arr)
col_sum = [Link](a, axis=0)
print("Column-wise sum:", col_sum)
14. a )Write a python program to demonstrate working with Sets in Python. (CO1)
b )Explain NumPy integer indexing, array indexing, Boolean array indexing and slicing
with examples. (CO4)
a)
s = set()
n = int(input("Enter number of elements: "))
for i in range(n):
[Link](int(input("Enter element: ")))
[Link](int(input("Enter element to add: ")))
[Link](int(input("Enter element to remove: ")))
print("Final set:", s)
b)
import numpy as np
a = [Link]([[1, 2, 3], [4, 5, 6]])
print(a[0][1])
print(a[0:2, 1:3])
b = [Link]([10, 20, 30, 40, 50])
print(b[[0, 2, 4]])
print(b[b > 25])
15. a)Write a python program to demonstrate working with Tuples in Python. (CO1)
b)Write a Pandas program to join the two given data frames along row and assign all data.
(CO4).
a)
t = ()
n = int(input("Enter number of elements: "))
lst = []
for i in range(n):
[Link](input("Enter element: "))
t = tuple(lst)
print("Tuple:", t)
print("After adding element:", t + tuple([input("Enter element to add: ")]))
x = input("Enter element to search: ")
if x in t:
print("Found")
else:
print("Not Found")
b)
import pandas as pd
data1 = {'A': [1, 2], 'B': [3, 4]}
data2 = {'A': [5, 6], 'B': [7, 8]}
df1 = [Link](data1)
df2 = [Link](data2)
result = [Link]([df1, df2], axis=0)
print(result)
16. a )Write a program that takes a range and creates a list of tuples within that range with the
first element as the number and the second element as the square of the number. (CO1)
b )Write a Pandas program to append rows to an existing Data Frame and display the
combined data. (CO4)
a)
start = int(input("Enter start value: "))
end = int(input("Enter end value: "))
result = []
for i in range(start, end + 1):
[Link]((i, i * i))
print("Result:", result)
b)
import pandas as pd
df = [Link]({'A': [1, 2], 'B': [3, 4]})
new_rows = [Link]({'A': [5, 6], 'B': [7, 8]})
df = [Link]([df, new_rows], ignore_index=True)
print(df)
17. a )Write a program to read a text file and count the occurrences of a specific word. CO2
b )Write a Pandas program to count the number of missing values in each column of a given
Data Frame (CO4)
a)
word = input("Enter word to search: ")
with open("[Link]", "r") as f:
text = [Link]()
count = [Link]().count(word)
print("Count:", count)
b)
import pandas as pd
df = [Link]({
'A': [1, None, 3],
'B': [None, 5, None],
'C': [7, 8, 9] })
print([Link]().sum())
18. a )Implement a program to extract specific lines containing a keyword from a text file and
write them to another file. CO2
b )Write Python program to add, subtract, multiply and divide two Pandas Series. (CO4)
a)
source = “F:\SJIT\python\[Link]”
Dest = “[Link]”
keyword = input(“Enter the keyword to search: “).lower()
with open(source, “r”) as f1, open(Dest, “w”) as f2:
for line in f1:
if keyword in [Link]():
[Link](line)
print(“Lines containing the word”, keyword, “are written to”, Dest)
b)
import pandas as pd
ds1 = [Link]([2, 4, 6, 8, 10])
ds2 = [Link]([1, 3, 5, 7, 9])
ds = ds1 + ds2
print("Add two Series:")
print(ds)
print("Subtract two Series:")
ds = ds1 - ds2
print(ds)
print("Multiply two Series:")
ds = ds1 * ds2
print(ds)
print("Divide Series1 by Series2:")
ds = ds1 / ds2
print(ds)