0% found this document useful (0 votes)
10 views

pdp lab codes

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

pdp lab codes

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

CODE:

class RetailStore:
def __init__(self, name, location, num_employees, operating_hours, inventory):
self.name = name
self.location = location
self.num_employees = num_employees
self.operating_hours = operating_hours
self.inventory = inventory

def add_item(self, item, quantity):


if item in self.inventory:
self.inventory[item] += quantity
else:
self.inventory[item] = quantity
print(f"Added {quantity} of {item} to the inventory.")

def remove_item(self, item, quantity):


if item in self.inventory and self.inventory[item] >= quantity:
self.inventory[item] -= quantity
print(f"Removed {quantity} of {item} from the inventory.")
else:
print(f"Cannot remove {quantity} of {item} from the inventory.")

def hire_employee(self):
self.num_employees += 1
print(f"One employee hired. Total employees: {self.num_employees}")

def fire_employee(self):
if self.num_employees > 0:
self.num_employees -= 1
print(f"One employee fired. Total employees: {self.num_employees}")
else:
print("No employees to fire.")

def display_inventory(self):
print("Inventory:")
for item, quantity in self.inventory.items():
print(f"{item}: {quantity}")

class ElectronicStore(RetailStore):
def __init__(self, name, location, num_employees, operating_hours, inventory, tech_support,
warranty_services, year_of_manufacture):
super().__init__(name, location, num_employees, operating_hours, inventory)
self.tech_support = tech_support
self.warranty_services = warranty_services
self.year_of_manufacture = year_of_manufacture
def provide_tech_support(self, customer_name):
if self.tech_support:
print(f"Providing tech support to {customer_name}.")
else:
print("Tech support is not available at this store.")

def extend_warranty(self, product_name, additional_years):


if self.warranty_services:
print(f"Extending warranty on {product_name} by {additional_years} years.")
else:
print("Warranty services are not available at this store.")

def run_product_demo(self, product_name):


if product_name in self.year_of_manufacture:
print(f"Running a demo for {product_name}, manufactured in
{self.year_of_manufacture[product_name]}.")
else:
print(f"Year of manufacture for {product_name} is not available.")

inventory = {
"Laptops": 50,
"Smartphones": 120,
"Tablets": 70,
}

year_of_manufacture = {
"Laptops": 2023,
"Smartphones": 2024,
"Tablets": 2022,
}

store = ElectronicStore(
name="Tech World",
location="Downtown",
num_employees=15,
operating_hours="9 AM - 9 PM",
inventory=inventory,
tech_support=True,
warranty_services=True,
year_of_manufacture=year_of_manufacture
)

store.hire_employee()
store.add_item("Headphones", 30)
store.display_inventory()

store.provide_tech_support("John Doe")
store.extend_warranty("Laptops", 2)
store.run_product_demo("Smartphones")

# COMPOSITION

class Student:
def __init__(self, name, roll_number, hometown):
self.name = name
self.roll_number = roll_number
self.hometown = hometown

def display_info(self):
return f"Name: {self.name}, Roll Number: {self.roll_number}, Hometown: {self.hometown}"

def modify_name(self, new_name):


self.name = new_name

def modify_hometown(self, new_hometown):


self.hometown = new_hometown

def modify_roll_number(self, new_roll_number):


self.roll_number = new_roll_number

class Department:
def __init__(self, department_name):
self.department_name = department_name
self.students = []

def add_student(self, student):


if isinstance(student, Student):
self.students.append(student)
else:
print("Only Student objects can be added.")

def display_info(self):
print(f"Department: {self.department_name}")
print("Students:")
for student in self.students:
print(student.display_info())

def get_number_of_students(self):
return len(self.students)

dept = Department("Electrical Engineering")

student1 = Student("Amit Sharma", 100, "Delhi")


student2 = Student("Priya Patel", 101, "Mumbai")
student3 = Student("Raj Kumar", 102, "Bangalore")
dept.add_student(student1)
dept.add_student(student2)
dept.add_student(student3)

print("Department Info:")
dept.display_info()

student1.modify_name("Amit Sinha")
student1.modify_hometown("Gurgaon")
student1.modify_roll_number(200)

print("\nUpdated Department Info:")


dept.display_info()

print("\nNumber of students in the department:", dept.get_number_of_students())

#AGGREGATION

class Employee:
def __init__(self, name, salary, emp_id, position):
self.name = name
self.salary = salary
self.emp_id = emp_id
self.position = position

def get_name(self):
return self.name

def get_salary(self):
return self.salary

def get_emp_id(self):
return self.emp_id

def get_position(self):
return self.position

def set_salary(self, salary):


self.salary = salary

def set_emp_id(self, emp_id):


self.emp_id = emp_id

def set_position(self, position):


self.position = position

def display_info(self):
return f"Name: {self.name}, Salary: ₹{self.salary:.2f}, Employee ID: {self.emp_id}, Position:
{self.position}"

class Project:
def __init__(self, project_name):
self.project_name = project_name
self.employees = []

def add_employee(self, employee):


self.employees.append(employee)

def remove_employee(self, employee):


if employee in self.employees:
self.employees.remove(employee)

def show_project_details(self):
print(f"Project: {self.project_name}")
print("Employees involved:")
for employee in self.employees:
print(employee.display_info())

emp1 = Employee("Alice", 80000, "E001", "Lead")


emp2 = Employee("Bob", 85000, "E002", "Senior")

proj = Project("Project Alpha")

proj.add_employee(emp1)
proj.add_employee(emp2)

print("Project Details:")
proj.show_project_details()

emp1.set_salary(90000)
emp1.set_position("Principal")

print("\nUpdated Project Details:")


proj.show_project_details()

proj.remove_employee(emp2)

print("\nProject Details After Removal:")


proj.show_project_details()
OUTPUT:
CODE:
import math

#1. Point class


class Point:
def __init__(self):
self.xcod = None
self.ycod = None

def getPoint(self):
self.xcod = int(input("Enter the value of xcod: "))
self.ycod = int(input("Enter the value of ycod: "))

def showPoint(self):
print("The value of xcod:", self.xcod)
print("The value of ycod:", self.ycod)

#2a Circle
class Circle:
def __init__(self):
self.center = Point()
self.orbit = Point()
self.radius = None
def getCircle(self):
print("Enter the coordinates of the center:")
self.center.getPoint()

print("Enter the coordinates of any point on the orbit:")


self.orbit.getPoint()

def calcRad(self):
self.radius = math.sqrt((self.orbit.xcod - self.center.xcod) ** 2 + (self.orbit.ycod -
self.center.ycod) ** 2)
return self.radius

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

#Cone
class Cone(Circle):
def __init__(self):
super().__init__()
self.apex = Point()
self.circle_1 = Circle()

def getApex(self):
print("Enter the coordinates of the apex of the cone:")
self.apex.getPoint()

def calcHeight(self):
self.height= math.sqrt((self.apex.xcod - self.center.xcod) ** 2 + (self.apex.ycod - self.center.ycod)
** 2)
return self.height

def getVolume(self):
if self.radius is None:
self.calcRad()
height = self.calcHeight()
volume = (1/3) * math.pi * self.radius ** 2 * height
return volume

#3 Regular Polygon
class Regular_Polygon(Point):
def __init__(self):
self.points_array = []
self.num_sides = 0

def getDetails(self):
self.num_sides = int(input("Enter the number of sides of the polygon: "))
for i in range(self.num_sides):
print(f"Enter the coordinates for point {i+1}:")
point = Point()
point.getPoint()
self.points_array.append(point)

#3a Square
class Square(Regular_Polygon):
def __init__(self):
super().__init__()
self.num_sides = 4
self.side_length = 0

def getDetails(self):
super().getDetails()

def calcSideLength(self):
if len(self.points_array) >= 2:
self.side_length = math.sqrt(
(self.points_array[1].xcod - self.points_array[0].xcod) ** 2 +
(self.points_array[1].ycod - self.points_array[0].ycod) ** 2
)
return self.side_length

def calcArea(self):
if self.side_length == 0:
self.calcSideLength()
return self.side_length ** 2

def calcPerimeter(self):
if self.side_length == 0:
self.calcSideLength()
return self.side_length * 4

def calcVolume(self):
if self.side_length == 0:
self.calcSideLength()
return self.side_length ** 3

print("### Point Class Demonstration ###")


point_obj = Point()
point_obj.getPoint()
point_obj.showPoint()

print("\n### Circle Class Demonstration ###")


circle = Circle()
circle.getCircle()
radius = circle.calcRad()
area = circle.calcArea()
print(f"Radius of the circle: {radius}")
print(f"Area of the circle: {area}")

print("\n### Cone Class Demonstration ###")


cone = Cone()
cone.getCircle()
cone.getApex()
height = cone.calcHeight()
volume = cone.getVolume()
print(f"Height of the cone: {height}")
print(f"Volume of the cone: {volume}")

print("\n### Square Class Demonstration ###")


square = Square()
square.getDetails()
side_length = square.calcSideLength()
area = square.calcArea()
perimeter = square.calcPerimeter()
volume = square.calcVolume()
print(f"Side length of the square: {side_length}")
print(f"Area of the square: {area}")
print(f"Perimeter of the square: {perimeter}")
print(f"Volume of the cube (assuming square is the base): {volume}")
OUTPUT:
CODE:
class EngineeringCollege:
def __init__(self, name, location, num_students, num_faculty):
self.name = name
self.location = location
self.num_students = num_students
self.num_faculty = num_faculty

def admit_rate(self, admitted_students):


if self.num_students == 0:
return 0
return (admitted_students / self.num_students) * 100

def student_faculty_ratio(self):
if self.num_students <= 0:
return "Invalid number of students."
if self.num_faculty <= 0:
return "No faculty members available."
return self.num_students / self.num_faculty

def set_student_count(self, new_count):


if new_count < 0:
return "Number of students cannot be negative."
self.num_students = new_count

def set_faculty_count(self, new_count):


if new_count < 0:
return "Number of faculty members cannot be negative."
self.num_faculty = new_count

def info(self):
return (f"Name: {self.name}\n"
f"Location: {self.location}\n"
f"Students: {self.num_students}\n"
f"Faculty: {self.num_faculty}")

college = EngineeringCollege("ABC University", "India", 5000, 300)

print(college.info())
print("Admission rate for 1000 admitted students:", college.admit_rate(1000))
print("Student to faculty ratio:", college.student_faculty_ratio(),"\n")

college.set_student_count(7500)
print("Updated Info:\n"+college.info())
print("Admission rate for 1000 admitted students:", college.admit_rate(1000))
print("Student to faculty ratio:", college.student_faculty_ratio(),"\n")
OUTPUT:
CODE:

Convert_module.py:
class ConvertModule:
def convert_hrs_days(hours):
return hours / 24

def convert_days_hours(days):
return days * 24

def convert_man_hrs_days(man_hours):
return man_hours / 8

current_module.py:
from datetime import datetime

class CurrentModule:
def current_time():
return datetime.now().strftime("%H:%M:%S")

def current_date_default():
return datetime.now().strftime("%d.%m.%Y")

def current_date_mmddyyyy():
return datetime.now().strftime("%m.%d.%Y")

def current_date_string():
return datetime.now().strftime("%A, %d %B %Y")

date_module.py:
from datetime import datetime

class DateModule:
def create_date(year, month, day):
return datetime(year, month, day)

def display_date(date_obj):
return date_obj.strftime("%d.%m.%Y")

difference_module.py:
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta

class DifferenceModule:
def difference_with_current(date_obj):
return datetime.now() - date_obj

def difference(date1, date2):


return date2 - date1

def days_after(date_obj, days):


return date_obj + timedelta(days=days)

def days_before(date_obj, days):


return date_obj - timedelta(days=days)

def month_after(date_obj, months):


return date_obj + relativedelta(months=+months)

def month_before(date_obj, months):


return date_obj - relativedelta(months=-months)

validity_module.py:
from datetime import datetime

class ValidityModule:
def is_valid_time(time_str):
try:
datetime.strptime(time_str, '%H:%M:%S')
return True
except ValueError:
return False

def is_valid_date(date_str):
try:
datetime.strptime(date_str, '%d.%m.%Y')
return True
except ValueError:
return False

__init__.py:
Pass

Competition.py:
from datetime import datetime
from DatePackage.date_module import DateModule
from DatePackage.current_module import CurrentModule
from DatePackage.convert_module import ConvertModule
from DatePackage.validity_module import ValidityModule
from DatePackage.difference_module import DifferenceModule

def get_student_details():
name = input("Enter student name: ")
dob_str = input("Enter date of birth (dd.mm.yyyy): ")

if not ValidityModule.is_valid_date(dob_str):
print("Invalid date format. Please use dd.mm.yyyy")
return None

dob = datetime.strptime(dob_str, "%d.%m.%Y")


age = DifferenceModule.difference_with_current(dob).days // 365

if age > 17:


print("Sorry, this competition is only for students under 17 years old.")
return None

registration_date = datetime.now()
expiry_date = DifferenceModule.days_after(registration_date, 180)

return {
"name": name,
"dob": dob,
"registration_date": registration_date,
"expiry_date": expiry_date
}

def check_registration_validity(student):
if student:
today = datetime.now()
age = DifferenceModule.difference_with_current(student["dob"]).days // 365
if age <= 17 and today <= student["expiry_date"]:
print(f"Registration for {student['name']} is still valid.")
else:
print(f"Registration for {student['name']} is no longer valid.")
else:
print("No valid student information found.")

student = get_student_details()
if student:
print(f"Registration successful! Valid until {student['expiry_date'].strftime('%d.%m.%Y')}.")

check_registration_validity(student)

OUTPUT:
CODE:

Node.py:
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data

binary_tree.py:
from abc import ABC, abstractmethod
from Node import Node

class BinaryTree(ABC):

@abstractmethod
def create_tree(self, iterable):
pass
@abstractmethod
def insert(self, data):
pass
@abstractmethod
def traverse_in_order(self):
pass
@abstractmethod
def traverse_pre_order(self):
pass
@abstractmethod
def traverse_post_order(self):
pass

binary_search_tree.py:
from binary_tree import BinaryTree
from Node import Node

class BinarySearchTree(BinaryTree):
def __init__(self):
self.root = None
def create_tree(self, iterable):
for item in iterable:
self.insert(item)

def insert(self, data):


if not self.root:
self.root = Node(data)
else:
self._insert(self.root, data)
def _insert(self, node, data):
if data < node.data:
if node.left is None:
node.left = Node(data)
else:
self._insert(node.left, data)
else:
if node.right is None:
node.right = Node(data)
else:
self._insert(node.right, data)

def traverse_in_order(self):
result = []
self._traverse_in_order(self.root, result)
return result

def _traverse_in_order(self, node, result):


if node:
self._traverse_in_order(node.left, result)
result.append(node.data)
self._traverse_in_order(node.right, result)

def traverse_pre_order(self):
result = []
self._traverse_pre_order(self.root, result)
return result

def _traverse_pre_order(self, node, result):


if node:
result.append(node.data)
self._traverse_pre_order(node.left, result)
self._traverse_pre_order(node.right, result)

def traverse_post_order(self):
result = []
self._traverse_post_order(self.root, result)
return result

def _traverse_post_order(self, node, result):


if node:
self._traverse_post_order(node.left, result)
self._traverse_post_order(node.right, result)
result.append(node.data)

Application.py:
from datetime import datetime
from binary_search_tree import BinarySearchTree
class NewsItem:
def __init__(self, date, category, content):
self.date = datetime.strptime(date, '%Y-%m-%d')
self.category = category
self.content = content

def __repr__(self):
return f"{self.date.strftime('%Y-%m-%d')} - {self.category} - {self.content}"

def __lt__(self, other):


return self.date < other.date

def main():
news_list = [
NewsItem('2024-09-01', 'Political', 'Election results are in.'),
NewsItem('2024-09-02', 'Sports', 'Local team wins championship.'),
NewsItem('2024-09-03', 'Political', 'New policy announcement.'),
NewsItem('2024-09-05', 'Sports', 'Player of the year awards.'),
]
political_tree = BinarySearchTree()
sports_tree = BinarySearchTree()

for news in news_list:


if news.category == 'Political':
political_tree.insert(news)
elif news.category == 'Sports':
sports_tree.insert(news)

def display_news_on_date(tree,date):
for news in tree.traverse_in_order():
if news.date.date() == date:
print(news)

def display_news_between_dates(tree,start_date,end_date):
for news in tree.traverse_in_order():
if start_date <= news.date.date() and end_date>= news.date.date():
print(news)

x_date = datetime.strptime('2024-09-02', '%Y-%m-%d').date()


print("News on date '2024-09-02' in Sports category:")
display_news_on_date(sports_tree, x_date)

d1_date = datetime.strptime('2024-09-01', '%Y-%m-%d').date()


d2_date = datetime.strptime('2024-09-04', '%Y-%m-%d').date()
print("\nNews between '2024-09-01' and '2024-09-04' in Political category:")
display_news_between_dates(political_tree, d1_date, d2_date)

if __name__ == "__main__":
main()

__init_.py:
from datetime import datetime
from BinaryTree.binary_search_tree import BinarySearchTree

OUTPUT:

CODE:
Arguments.py:

def average(*args):
if len(args) == 0:
return 0
return sum(args) / len(args)

print("Average:",average(10, 20, 30))


print("Average:",average(5, 10))

print("\n")

def ShowOff(**kwargs):
if 'marks' in kwargs and kwargs['marks'] > 60:
print(f"Name: {kwargs.get('name', 'Unknown')}, Marks: {kwargs['marks']}")
else:
subject = kwargs.get('subject', 'Unknown Subject')
teacher = kwargs.get('teacher', 'Unknown Teacher')
print(f"Name: {kwargs.get('name', 'Unknown')}, Subject: {subject}, Teacher: {teacher}")

ShowOff(name="Max", marks=75)
ShowOff(name="Bob", marks=55, subject="Math", teacher="Smith")
OUTPUT:
CODE:
# Q1
class VectorSizeMismatchException(Exception):
pass

class EmptyVectorException(Exception):
pass

class IntegerVector(list):
def __init__(self, *args):
for arg in args:
if not isinstance(arg, int):
raise TypeError("Only integers are allowed in IntegerVector")
super().__init__(args)

def __setitem__(self, index, value):


if not isinstance(value, int):
raise TypeError("Only integers are allowed in IntegerVector")
super().__setitem__(index, value)

def append(self, value):


if not isinstance(value, int):
raise TypeError("Only integers are allowed in IntegerVector")
super().append(value)

def __add__(self, other):


if not isinstance(other, IntegerVector):
raise TypeError("Operand must be of type IntegerVector")
max_len = max(len(self), len(other))
result = IntegerVector()
for i in range(max_len):
value_self = self[i] if i < len(self) else 0
value_other = other[i] if i < len(other) else 0
result.append(value_self + value_other)
return result

def __sub__(self, other):


if not isinstance(other, IntegerVector):
raise TypeError("Operand must be of type IntegerVector")
max_len = max(len(self), len(other))
result = IntegerVector()
for i in range(max_len):
value_self = self[i] if i < len(self) else 0
value_other = other[i] if i < len(other) else 0
result.append(value_self - value_other)
return result

def GetRatios(Vec1, Vec2):


if len(Vec1) == 0 and len(Vec2) == 0:
raise EmptyVectorException("Both vectors are of zero length.")

if len(Vec1) != len(Vec2):
raise VectorSizeMismatchException("The sizes of the vectors are different.")

Ratio = []
for i in range(len(Vec1)):
try:
if Vec2[i] == 0:
Ratio.append('NaN')
else:
Ratio.append(Vec1[i] / Vec2[i])
except ZeroDivisionError:
Ratio.append('NaN')
except Exception as e:
print(f"An unexpected error occurred at index {i}: {e}")

return Ratio

V1 = IntegerVector(4, 5, 6)
V2 = IntegerVector(2, 0, 3)

V3 = V1 + V2
V4 = V1 - V2

print("V1 + V2 =", V3)


print("V1 - V2 =", V4)

try:
ratios = GetRatios(V1, V2)
print("Ratio Vector:", ratios)
except EmptyVectorException as e:
print(e)
except VectorSizeMismatchException as e:
print(e)
except Exception as e:
print("An unexpected error occurred:", e)

print("\n")

# Q2
class Employee:
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
@classmethod
def from_string(cls, full_name):
first_name, last_name = full_name.split()
return cls(first_name, last_name)

def display(self):
print(f"Employee Name: {self.first_name} {self.last_name}")

emp1 = Employee("John", "Cena")


emp1.display()

emp2 = Employee.from_string("Seetha Raman")


emp2.display()

print("\n")

# Q3

class Movie:
def __init__(self, title, genre):
self.title = title
self.genre = genre

def __str__(self):
return f"{self.title} ({self.genre})"

class MovieList(list):
def __init__(self, genre):
self.genre = genre
super().__init__()

def append(self, movie):


if isinstance(movie, Movie) and movie.genre == self.genre:
super().append(movie)
else:
raise TypeError(f"Cannot add movie: {movie.title}. Genre mismatch.")

def __str__(self):
return f"Movie List ({self.genre}): " + ", ".join(str(movie) for movie in self)

def __len__(self):
return super().__len__()

def __gt__(self, other):


if not isinstance(other, MovieList):
return NotImplemented
return len(self) > len(other)
def __add__(self, other):
if not isinstance(other, MovieList) or self.genre != other.genre:
raise TypeError(f"Cannot combine movie lists of different genres.")
combined_list = MovieList(self.genre)
combined_list.extend(self)
combined_list.extend(other)
return combined_list

movie1 = Movie("Inception", "thriller")


movie2 = Movie("Interstellar", "sci-fi")
movie3 = Movie("The Dark Knight", "thriller")
movie4 = Movie("The Matrix", "sci-fi")

thriller_list = MovieList("thriller")
sci_fi_list = MovieList("sci-fi")

thriller_list.append(movie1)
thriller_list.append(movie3)

sci_fi_list.append(movie2)
sci_fi_list.append(movie4)

print(thriller_list)
print(sci_fi_list)

try:
thriller_list.append(movie2)
except TypeError as e:
print(e)

combined_list = thriller_list + thriller_list


print(combined_list)

if thriller_list > sci_fi_list:


print("Thriller list has more movies.")
else:
print("Sci-fi list has more movies.")

OUTPUT:
CODE:

import re
hello = {
"Hindi": "स्वागत है",
"Bengali": "স্বাগতম",
"Telugu": "స్వాగతం",
"Marathi": "स्वागत आहे",
"Tamil": "வணக்கம்",
"Gujarati": "સ્વાગત છે",
"Kannada": "ಸ್ವಾಗತ",
"Malayalam": "സ്വാഗതം",
"Odia": "ସ୍ୱାଗତ",
"Punjabi": "ਸੁਆਗਤ ਹੈ",
"Urdu": "‫"خوش آمدید‬,
"Assamese": "স্বাগতম",
"Konkani": "स्वागत",
"Sanskrit": "स्वागतं",
"Kashmiri": "‫"خۆش آمەدی‬
}

name = input("Enter your name: ")


language = input("Enter the language (choose from Hindi, Bengali, Telugu, Marathi, Tamil, Gujarati,
Kannada, Malayalam, Odia, Punjabi, Urdu, Assamese, Konkani, Sanskrit, Kashmiri): ")

if language in hello:
print(f"{hello[language]} {name}!")
else:
print(f"Sorry, {language} is not in our list.")

class stock:
def __init__(self,file):
self.file = file

def read_text(self):
with open(self.file,'r') as files:
file_content = [line.rstrip() for line in files]
print(file_content)
return file_content

def display_text(self):
lines = self.read_text()
for i in lines:
print(i)

obj = stock('stock.txt')
obj.display_text()

#q02
print('\n')
def read_spam_words(spam_file):
with open(spam_file,'r') as file1:
spam_words = file1.read().splitlines()
return spam_words

def read_file(user_file):
with open(user_file,'r') as file2:
content = file2.read().lower()
words = re.findall(r'\b\w+\b', content)
return words

def check_spam_content(spam_words,words):
spam_count = sum ( 1 for word in words if word in spam_words)
spam_percentage = (spam_count/len(words)) * 100
return spam_count,spam_percentage

def replace_spam_words(spam_words,words):
replaced_words = [words if word not in spam_words else '' for word in words]
return ' '.join(replaced_words)

def write_file(replaced_content,file_name):
with open(file_name,'w') as file:
file.write(replaced_content)

def main():
spam_file = 'bag_of_spam.txt'
spam_words = read_spam_words(spam_file)

user_file = 'test.txt'
words = read_file(user_file)

spam_count,spam_percentage = check_spam_content(spam_words,words)

if spam_percentage >= 40:


print(f"The {user_file} is considered as a Spam file.spam cotent:{spam_percentage:.2f}%")
else:
print(f"The {user_file} is considered a Genuine file.spam content:{spam_percentage:.2f}%")

if __name__ == "__main__":
main()

OUTPUT:
CODE:
#ex 7
import re

class check_password:
def __init__(self,input):
self.input_str = input

def password_validity_check(self):
self.valid_password = r'^[a-zaA-Z\d!@#$%^&*]{8,}$'
if re.match(self.valid_password,self.input_str):
return f"{self.input_str} is a valid password"
else:
return f"{self.input_str} is not valid password"
def variable_validity_check(self):
self.valid_string = r'[a-zA-Z][a-zA-Z\d_]*$'
if re.match(self.valid_string,self.input_str):
return f"{self.input_str} is a valid string"
else:
return f"{self.input_str} is not valid string"

def binary_validity_check(self):
self.valid_binary = r'^[01]+$'
if re.match(self.valid_binary,self.input_str):
return f"{self.input_str} is a valid binary numbers"
else:
return f"{self.input_str} is not valid binary numbers"

valid_password_test = check_password("StrongP@ss1")
print(valid_password_test.password_validity_check())
invalid_password_test = check_password("short1")
print(invalid_password_test.password_validity_check())

valid_var_test = check_password("valid_variable1")
print(valid_var_test.variable_validity_check())
invalid_var_test = check_password("1_invalid_var")
print(invalid_var_test.variable_validity_check())

valid_binary_test = check_password("110101")
print(valid_binary_test.binary_validity_check())
invalid_binary_test = check_password("11012")
print(invalid_binary_test.binary_validity_check())
print("\n")

#q4
import re

class SentenceParser:
def __init__(self):
self.verbs = r'\b(cut|cuts|cut|sing|sings|sang|dance|dances|danced|fell|falls|eat|eats|ate|
drink|drinks|drank|take|takes|took|play|plays|played|beat|beats)\b'
self.subjects = r'\b(Ram|Mohan|Kavin|A\schild|He|She|They|People|Boys|Girls|The\stree|
The\sLollypop|The\smilk|Cat|The\scat|Milk)\b'
self.objects = r'\b(the tree|the trees|Lollypop|lollypops|milk|cat|cats|cake|cakes)\b'

self.sentence_pattern = re.compile(rf'^({self.subjects})\s+({self.verbs})\s+({self.objects}|
{self.subjects})')

def validate_sentence(self,sentence):
if self.sentence_pattern.match(sentence):
return "Valid"
else:
return "Invalid"

parser = SentenceParser()
test_sentences = [
"Ram cuts the tree.",
"Mohan beats Kavin",
"A child ate Lollypop",
"Drink milk cat",
"Milk drinks cat"]
for sentence in test_sentences:
result = parser.validate_sentence(sentence)
print(f"'{sentence}': {result}")

OUTPUT:

You might also like