1.
Write a Python program for class, Flower, that has three instance variables of type str,int, and float,
that respectively represent the name of the flower, its number of petals, and its price. Your class must
include a constructor method that initializes each variable to an appropriate value, and your class should
include methods for setting the value of each type, and retrieving the value of each type.
class Flower:
def __init__(self, name, petals, price):
self.name = name
self.petals = petals
self.price = price
def set_name(self, name):
self.name = name
def set_petals(self, petals):
self.petals = petals
def set_price(self, price):
self.price = price
def get_name(self):
return self.name
def get_petals(self):
return self.petals
def get_price(self):
return self.price
if __name__ == "__main__":
rose = Flower("Rose", 24, 5.99)
print("Initial Flower Details:")
print("Name:", rose.get_name())
print("Petals:", rose.get_petals())
print("Price: $", rose.get_price())
print()
rose.set_name("Red Rose")
rose.set_petals(20)
rose.set_price(4.99)
print("Updated Flower Details:")
print("Name:", rose.get_name())
print("Petals:", rose.get_petals())
print("Price: $", rose.get_price())
output:
Initial Flower Details:
Name: Rose
Petals: 24
Price: $ 5.99
Updated Flower Details:
Name: Red Rose
Petals: 20
Price: $ 4.99
2. Develop an inheritance hierarchy based upon a Polygon class that has abstract methods area( ) and
perimeter( ). Implement classes Triangle, Quadrilateral, Pentagon, that extend this base class, with the
obvious meanings for the area( ) and perimeter( ) methods. Write a simple program that allows users to
create polygons of the various types and input their geometric dimensions, and the program then outputs
their area and perimeter.
fromabc import ABC, abstractmethod
import math
class Polygon(ABC):
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
class Triangle(Polygon):
def __init__(self, side1, side2, side3):
self.side1 = side1
self.side2 = side2
self.side3 = side3
def area(self):
s = (self.side1 + self.side2 + self.side3) / 2
returnmath.sqrt(s * (s - self.side1) * (s - self.side2) * (s - self.side3))
def perimeter(self):
return self.side1 + self.side2 + self.side3
class Quadrilateral(Polygon):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
returnself.width * self.height
def perimeter(self):
return 2 * (self.width + self.height)
class Pentagon(Polygon):
def __init__(self, side):
self.side = side
def area(self):
return (1 / 4) * math.sqrt(5 * (5 + 2 * math.sqrt(5))) * (self.side ** 2)
def perimeter(self):
return 5 * self.side
def main():
print("Choose polygon type (triangle, quadrilateral, pentagon): ")
polygon_type = input().strip().lower()
ifpolygon_type == "triangle":
print("Enter side1, side2, side3:")
side1 = float(input())
side2 = float(input())
side3 = float(input())
polygon = Triangle(side1, side2, side3)
elifpolygon_type == "quadrilateral":
print("Enter width and height:")
width = float(input())
height = float(input())
polygon = Quadrilateral(width, height)
elifpolygon_type == "pentagon":
print("Enter side length:")
side = float(input())
polygon = Pentagon(side)
else:
print("Unknown polygon type.")
return
print(f"Area: {polygon.area():.2f}")
print(f"Perimeter: {polygon.perimeter():.2f}")
if __name__ == "__main__":
main()
output:
Choose polygon type (triangle, quadrilateral, pentagon):
triangle
Enter side1, side2, side3:
5
8
9
Area: 19.90
Perimeter: 22.00
Choose polygon type (triangle, quadrilateral, pentagon):
quadrilateral
Enter width and height:
5
8
Area: 40.00
Perimeter: 26.00
Choose polygon type (triangle, quadrilateral, pentagon):
pentagon
Enter side length:
12
Area: 247.75
Perimeter: 60.00
3. Develop an inheritance hierarchy based upon a Polygon class that has abstract area() and perimeter().
From abc import ABC #This will import the ABC class
Class Polygon(ABC): # Now the code should be able to find the ABC class
@abstractmethod
defarea(self):
pass
@abstractmethod
defperimeter(self):
pass
class Triangle(Polygon):
def__init__(self, side1, side2, side3):
self.side1 = side1
self.side2 = side2
self.side3 = side3
defarea(self):
s = (self.side1 + self.side2 + self.side3) / 2
returnmath.sqrt(s * (s - self.side1) * (s - self.side2) * (s - self.side3))
defperimeter(self):
returnself.side1 + self.side2 + self.side3
class Quadrilateral(Polygon):
def__init__(self, width, height):
self.width = width
self.height = height
defarea(self):
returnself.width * self.height
defperimeter(self):
return2 * (self.width + self.height)
class Pentagon(Polygon):
def__init__(self, side):
self.side = side
defarea(self):
return (1 / 4) * math.sqrt(5 * (5 + 2 * math.sqrt(5))) * (self.side ** 2)
defperimeter(self):
return5 * self.side
defmain():
print("Choose polygon type (triangle, quadrilateral, pentagon): ")
polygon_type = input().strip().lower()
if polygon_type == "triangle":
print("Enter side1, side2, side3:")
side1 = float(input())
side2 = float(input())
side3 = float(input())
polygon = Triangle(side1, side2, side3)
elif polygon_type == "quadrilateral":
print("Enter width and height:")
width = float(input())
height = float(input())
polygon = Quadrilateral(width, height)
elif polygon_type == "pentagon":
print("Enter side length:")
side = float(input())
polygon = Pentagon(side)
else:
print("Unknown polygon type.")
return
print(f"Area: {polygon.area():.2f}")
print(f"Perimeter: {polygon.perimeter():.2f}")
if__name__ == "__main__":
main()
OUTPUT
Choose polygon type (triangle, quadrilateral, pentagon):
triangle
Enter side1, side2, side3:
5
8
7
Area: 17.32
Perimeter: 20.00
4. Write a python program to implement Method Overloading and Method Overriding.
class Shape:
def __init__(self, name):
self.name = name
# Method overriding: This method is overridden by subclasses
def draw(self):
print(f"Drawing a {self.name}")
class Circle(Shape):
def __init__(self, name, radius=None):
super().__init__(name)
self.radius = radius
# Method overriding: This method overrides the draw method in Shape
def draw(self):
ifself.radius is not None:
print(f"Drawing a {self.name} with radius {self.radius}")
else:
print(f"Drawing a {self.name} with unknown radius")
# Method overloading using default arguments
defset_radius(self, radius=None):
if radius is not None:
self.radius = radius
else:
returnself.radius
class Rectangle(Shape):
def __init__(self, name, width=None, height=None):
super().__init__(name)
self.width = width
self.height = height
# Method overriding: This method overrides the draw method in Shape
def draw(self):
ifself.width is not None and self.height is not None:
print(f"Drawing a {self.name} with width {self.width} and height {self.height}")
else:
print(f"Drawing a {self.name} with unknown dimensions")
# Method overloading using *args
defset_dimensions(self, *args):
iflen(args) == 1:
self.width = args[0]
eliflen(args) == 2:
self.width = args[0]
self.height = args[1]
else:
print("Invalid number of arguments")
def main():
# Creating Shape objects
shape1 = Circle(name="Circle", radius=5)
shape2 = Rectangle(name="Rectangle", width=10, height=20)
# Drawing shapes
shape1.draw() # Should print: Drawing a Circle with radius 5
shape2.draw() # Should print: Drawing a Rectangle with width 10 and height 20
# Demonstrating method overloading
shape1.set_radius() # Returns the current radius
shape1.set_radius(10) # Sets a new radius
shape2.set_dimensions(15) # Sets width to 15
shape2.set_dimensions(15, 25) # Sets width to 15 and height to 25
print(f"New radius of shape1: {shape1.set_radius()}")
print(f"New dimensions of shape2: width={shape2.width}, height={shape2.height}")
if __name__ == "__main__":
main()
Output:
Drawing a Circle with radius 5
Drawing a Rectangle with width 10 and height 20
New radius of shape1: 10
New dimensions of shape2: width=15, height=25
5. Write a Python program that inputs a list of words, separated by whitespace, and outputs how many
times each word appears in the list.
def count_words(word_list):
# Indent the lines within the function body
word_counts = {}
words = word_list.split()
for word in words:
if word in word_counts:
word_counts[word] += 1
else:
word_counts[word] = 1
return word_counts # Fixed typo: 'returnword_counts' should be 'return word_counts'
# Input list of words
input_words = input("Enter a list of words separated by whitespace: ")
# Count occurrences of each word
word_counts = count_words(input_words)
# Print the word counts
print("Word counts:")
for word, count in word_counts.items():
print(f"{word}: {count}")
OUTPUT:
Enter a list of words separated by whitespace: THIS IS INDIA
Word counts:
THIS: 1
IS: 1
INDIA: 1
6.Write a Python program to illustrate the following comprehensions: a) List Comprehensions b)
Dictionary Comprehensions c) Set Comprehensions d) Generator Comprehensions
a) List Comprehensions
squares = [x ** 2 for x in range(1, 7)]
print("List comprehension (squares):", squares)
List comprehension (squares): [1, 4, 9, 16, 25, 36]
b) Dictionary Comprehensions
square_dict = {x: x ** 2 for x in range(1, 7)}
print("Dictionary comprehension (square_dict):", square_dict)
Dictionary comprehension (square_dict): {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36}
c) Set Comprehensions
square_set = {x ** 2 for x in range(1, 6)}
print("Set comprehension (square_set):", square_set)
Set comprehension (square_set): {1, 4, 9, 16, 25}
d) Generator Comprehensions
square_generator = (x ** 2 for x in range(1, 7))
print("Generator comprehension (square_generator):", square_generator)
print("Generated values:")
for num in square_generator:
print(num, end=" ")
print()
Generator comprehension (square_generator): <generator object <genexpr> at
0x78ac843d4e40>
Generated values:
1 4 9 16 25 36
7.Write a Python program to implement Method Overloading and Method Overriding
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def displayData(self):
print('In parent class displayData method')
print(self.name)
print(self.age)
class Employee(Person):
def __init__(self, name, age, id):
# calling constructor of super class
super().__init__(name, age)
self.empId = id
def displayData(self):
print('In child class displayData method')
print(self.name)
print(self.age)
print(self.empId)
#Person class object
person = Person('Karthik Shaurya', 26)
person.displayData()
#Employee class object
emp = Employee('Karthik Shaurya', 26, 'E317')
emp.displayData()
OUTPUT
In parent class displayData method
Karthik Shaurya
26
In child class displayData method
Karthik Shaurya
26
E317
8. Write a Python program to generate the combinations of n distinct objects taken from the elements of
a given list. Example: Original list: [1, 2, 3, 4, 5, 6, 7, 8, 9] Combinations of 2 distinct objects: [1, 2] [1,
3] [1, 4] [1, 5] [7, 8] [7, 9] [8, 9].
from itertools import combinations
def generate_combinations(original_list, n):
# Generate combinations of n distinct objects from the original_list
comb = combinations(original_list, n)
# Print the combinations
print(f"Combinations of {n} distinct objects:")
for c in comb:
print(list(c))
# Example usage:
original_list = [1, 2, 3, 4, 5, 6, 7]
n=2
generate_combinations(original_list, n)
Combinations of 2 distinct objects:
[1, 2]
[1, 3]
[1, 4]
[1, 5]
[1, 6]
[1, 7]
[2, 3]
[2, 4]
[2, 5]
[2, 6]
[2, 7]
[3, 4]
[3, 5]
[3, 6]
[3, 7]
[4, 5]
[4, 6]
[4, 7]
[5, 6]
[5, 7]
[6, 7]
9. Write a program for Linear Search and Binary search.
LINEAR SEARCH
def linearSearch(target, List):
position = 0
global iterations
iterations = 0
while position < len(List):
iterations += 1 # Indented this line to be inside the while loop
if target == List[position]:
return position
position += 1
return -1
if __name__ == '__main__':
List = [1, 2, 3, 4, 5, 6, 7, 8]
target = 3
answer = linearSearch(target, List)
if answer != -1:
print('Target found at index :', answer, 'in',
iterations,'iterations')
else:
print('Target not found in the list')
OUTPUT:
Target found at index : 2 in 3 iterations
BINARY SEARCH:
def binarySearch(target, List):
left = 0
right = len(List) - 1
global iterations
iterations = 0
while left <= right:
# The following line was not indented correctly
iterations += 1
mid = (left + right) // 2
if target == List[mid]:
return mid
elif target < List[mid]:
right = mid - 1
else:
left = mid + 1
return -1
if __name__ == '__main__':
List = [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14]
target = 12
answer = binarySearch(target, List)
if(answer != -1):
print('Target',target,'found at position', answer, 'in',
iterations,'iterations')
else:
print('Target not found')
OUTPUT:
Target 12 found at position 10 in 4 iterations
9. Write a program to implement Bubble Sort and Selection Sort
Bubble Sort
def bubble_sort(alist):
for i in range(len(alist) - 1, 0, -1):
no_swap = True
for j in range(0, i):
if alist[j + 1] < alist[j]:
alist[j], alist[j + 1] = alist[j + 1], alist[j]
no_swap = False
if no_swap:
return
alist = input('Enter the list of numbers: ').split()
alist = [int(x) for x in alist]
bubble_sort(alist)
print('Sorted list: ', alist)
OUTPUT:
Enter the list of numbers: 5 3 4 8 9 2
Sorted list: [2, 3, 4, 5, 8, 9]
Selection Sort
def selection_sort(alist):
for i in range(0, len(alist) - 1):
smallest = i # This line and the following lines should be indented
for j in range(i + 1, len(alist)):
if alist[j] < alist[smallest]:
smallest = j
alist[i], alist[smallest] = alist[smallest], alist[i]
alist = input('Enter the list of numbers: ').split()
alist = [int(x) for x in alist]
selection_sort(alist)
print('Sorted list: ', alist)
OUTPUT:
Enter the list of numbers: 5 9 6 4 2 8
Sorted list: [2, 4, 5, 6, 8, 9]