pdp lab codes
pdp lab codes
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 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.")
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}"
class Department:
def __init__(self, department_name):
self.department_name = department_name
self.students = []
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)
print("Department Info:")
dept.display_info()
student1.modify_name("Amit Sinha")
student1.modify_hometown("Gurgaon")
student1.modify_roll_number(200)
#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 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 show_project_details(self):
print(f"Project: {self.project_name}")
print("Employees involved:")
for employee in self.employees:
print(employee.display_info())
proj.add_employee(emp1)
proj.add_employee(emp2)
print("Project Details:")
proj.show_project_details()
emp1.set_salary(90000)
emp1.set_position("Principal")
proj.remove_employee(emp2)
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()
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
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 info(self):
return (f"Name: {self.name}\n"
f"Location: {self.location}\n"
f"Students: {self.num_students}\n"
f"Faculty: {self.num_faculty}")
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
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
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 traverse_in_order(self):
result = []
self._traverse_in_order(self.root, result)
return result
def traverse_pre_order(self):
result = []
self._traverse_pre_order(self.root, result)
return result
def traverse_post_order(self):
result = []
self._traverse_post_order(self.root, result)
return result
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 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()
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)
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("\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)
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
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}")
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 __str__(self):
return f"Movie List ({self.genre}): " + ", ".join(str(movie) for movie in self)
def __len__(self):
return super().__len__()
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)
OUTPUT:
CODE:
import re
hello = {
"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 __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: