0% found this document useful (0 votes)
74 views12 pages

749 Assignment 2

Uploaded by

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

749 Assignment 2

Uploaded by

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

• SU?t&lt1 PAUL
1

ROEE. NO. : 7/49;/ 22


eow:asE
UNI TY:. 2l010S03021
:RO . .

TER : IV
- - - - - - - -•1 •---=-- =- - - - - - - -
Ql) Write a code to display the following pattern
1
22
333
4444
55555

# Pattern 1: Increasing numbers


for i in range(l, 6):
print(str(i) * i)
1
21
321
4321
54321

# Pattern 2: Decreasing numbers


for i in range(l, 6):
print(".join(str(j) for j in range(i, O, -1)))
-------------•1 •---=-- =- ------------
Q2) Write a program to calculate the length of a
string without using the len() function

def calculate_length(input_string):
length= 0
for_ in input_string:
length+= 1
return length

# Test the function


user_input = input("Enter a string:")
length= calculate_length(user_input)
print("Length of the string is:", length)

Write a program to convert uppercase letters


Q3) to lowercase and vice-versa

def convert_case(input_string):
converted_string = 1111
for char in input_string:
if char.isupper():
converted_string += char.lower()
elif char.islower():
converted_string += char.upper()
else:
converted_string += char # Keep non-alphabetic characters unchanged
return converted_string

# Test the function


user_input = input("Enter a string: 11 )
converted_output = convert_case(user_input)
print("Converted string:", converted_output)
---------------1 •---=-- =- -------------
Q4) Write the code of using super function () and
overriding base class method

class BaseClass:
def greet(self):
print("Hello from BaseClass")

class DerivedClass(BaseClass):
def greet(self):
super().greet() # Calls the greet method from the BaseClass
print("Hello from DerivedClass")

# Creating an instance of the Derived Class


obj = DerivedClass()

# Calling the overridden greet method


obj.greet()

Q5) Program to demonstrate multiple inheritance


with method overriding
class BaseClassl:
def greet(self):
print("Hello from BaseClassl")

class BaseClass2:
def greet(self):
print("Hello from BaseClass2")

class DerivedClass(BaseClassl, BaseClass2):


def greet(self):
super().greet() # Calls the greet method from BaseClassl
print("Hello from DerivedClass")

# Creating an instance of DerivedClass


obj = DerivedClass()

# Calling the overridden greet method


obj.greet()
-----------------~----=-- =- ---------------
Program to demonstrate the solving of
Q6) diamond program in python
class A:
def greet(self):
print("Hello from A")

class B(A):
def greet(self):
print("Hello from 8 11 )

class C(A):
def greet(self):
print("Hello from C")

class D(B, C):


pass

# Creating an instance of D
obj= DO

# Calling the greet method


obj.greet()

# Print the method resolution order (MRO)


print(D.mro())

Q7) Write python program to create a class as vector and


implement _add_() method to add the two vector
numbers, display the result by operator overloading
class Vector:
def _init_(self, x, y):
self.x = x
self.y = y

def _add_(self, other):


if isinstance(other, Vector): # Check if 'other' is an instance of Vector
return Vector(self.x + other.x, self.y + other.y)
else:
raise TypeError("Unsupported operand type for+: Vector and O".format(type(other)))

def _str_(self):
return"({}, {})".format(self.x, self.y)

# Creating two Vector objects


vl = Vector(3, 5)
v2 = Vector(2, 7)

# Adding the vectors using operator overloading


result= vl + v2

# Displaying the result


print("Result of vector addition:", result)
---------------11•---=-- =- -------------
QS) Create a class named quadratic,where a,b,c are data
attributes & the methofd _init_() to initialize the data
attributes anf find the roots of the quadratic equation

import math

class Quadratic:
def _ init_ (self, a, b, c):
self.a= a
self.b = b
self.c = c

def find_roots(self):
discriminant= self.b**2 - 4*self.a*self.c

if discriminant > 0:
rootl = (-self.b + math.sqrt(discriminant)) / (2*self.a)
root2 = (-self.b - math.sqrt(discriminant)) / (2*self.a)
print("Roots are real and distinct.")
print("Root l:", rootl)
print("Root 2:", root2)
elif discriminant== O:
root= -self.b / (2*self.a)
print("Roots are real and equal.")
print("Root:", root)
else:
real_part = -self.b / (2*self.a)
imaginary_part = math.sqrt(abs(discriminant)) / (2*self.a)
print("Roots are complex.")
print("Root l:", real_part, "+", imaginary_part, "i")
print("Root 2:", real_part, "-", imaginary_part, "i")

# Creating a Quadratic object and finding roots


quadratic_eq = Quadratic(l, -5, 6)
quadratic_eq.find_roots()
---------------~----=-- =- -------------
Q12) Create two base classes named clock and calendar,
based on these two class define a class calendar clock
which inherit from both classes and display month
details date and time

class Clock:
def _init_(self, hour, minute, second):
self.hour= hour
self.minute= minute
self.second = second

def display_time(self):
print("Time:", f"{self.hour:02d}:{self.minute:02d}:{self.second:02d}")

class Calendar:
def _init_(self, day, month, year):
self.day = day
self.month = month
self.year= year

def display_date(self):
print{"Date:", f"{self.day:02d}-{self.month:02d}-{self.year}")

class CalendarClock(Clock, Calendar):


def _init_(self, hour, minute, second, day, month, year):
Clock._init_(self, hour, minute, second)
Calendar._init_(self, day, month, year)

def display_calendar_clock(self):
self.display_date()
self.display_time()

# Creating an instance of CalendarClock


calendar_clock= CalendarClock(l0, 30, 45, 12, 5, 2024)

# Displaying month details, date, and time


calendar_clock.display_calendar_clock()
------------------~----=-- =- ----------------
Q13) Write a program to add two polynomial using classes
class Polynomial:
def _init_(self, *coefficients):
self.coefficients ; coefficients[::-1] # Reverse the coefficients for easy access

def _add_(self, other):


result_coefficients = []
max_len = max(len(self.coefficients), len(other.coefficients))

for i in range(max_len):
coeff_sum = 0
if i < len(self.coefficients):
coeff_sum+= self.coefficients[i)
if i < len(other.coefficients):
coeff_sum+= other.coefficients[i)
result_coefficients.append(coeff_sum)

return Polynomial(* result_coefficients(::-1)) # Reverse the result coefficients

def d isplay_polynomial(self):
terms=[)
for power, coeff in enumerate(self.coefficients[::-1)):
if coeff != 0 :
if power == 0:
term = str(coeff)
elif power == 1:
term = f "{coeff}x"
else:
term = f"{coeff}x"{power}"
terms.append(term)
polynomial_str =" + " .join(terms)
print("Polynomial:", polynomial_str)

# Creating two polynomial objects


polyl = Polynomial(2, 0 , 5, 1) # 2x"3 + Sx + 1
poly2 = Polynomial(-3, 1, 0 , 2) # -3x" 3 + x"2 + 2

# Adding the polynomials


result_poly = polyl + poly2

# Displaying the original and result polynomials


print(" Polynomial 1:")
polyLdisplay_polynomial()
print(" \nPolynomial 2:")
poly2.display_polynomial()
print("\nResultant Polynomial:")
result_poly .display_polynomial()
---------------11•---=-- =- -------------
Q14) Write a python program to find out the product of
elements of two different lists using lambda function.

# Define two lists


listl = [1, 2, 3 , 41
list2 = [5, 6, 7, 8]

# Calculate the product of elements using lambda function


product = lambda x, y: x * y

# Calculate the product of corresponding elements from both lists


result= [product(x, y) for x, yin zip(listl, list2)]

# Display the result


print("List l :", listl)
print("List 2:", list2)
print("Product of corresponding elements:", result)

Q15 )A python program to access list elements using loops


# Define a list
my_list = [10, 20, 30, 40, 50]

# Using a for loop to access elements in the list


print("Using for loop:")
for element in my_list:
print( element)

# Using a while loop and index to access elements in the list


print("\nUsing while loop:")
index= 0
while index< len(my_list):
print(my_list[index])
index+= 1
------------11•---=-- =- ----------
Q16) A python program to display the elements of a list in
reverse order

# Define a list
my_list = [10, 20, 30, 40, 50]

# Using list slicing to reverse the list


reversed_list = my_list[::-1]

# Displaying the reversed list


print("Original List:", my_list)
print("Reversed List:\ reversed_list)

Ql7) Write a code to turn nested list [[1,2,3],[4,5,6],[7,8,9]]

nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]


flat_list = [item for sublist in nested_list for item in sublist]

print("Original Nested List:", nested_list)


print("Flattened List:", flat_list)
--------------11•---=-- =- ------------
Q18) ~ython program to find common elements between tw<
lists

# Create a d ictionary
my_dict = {'a' : 10, 'b': 20, 'c': 30, 'd ': 40}

# Calculate the sum of values in the dictionary


sum_values = sum(my_dict.values())

# Display the dictionary and the sum of values


print("Dictionary:", my_dict)
print("Sum of values:", sum_values)

Q19 )A python program to access the key value data


# Create a dictionary
my_dict = {'a': 10, 'b': 20, 'c': 30, 'd': 40}

# Access key-value pairs using a for loop


print("Accessing key-value pairs using a for loop:")
for key, value in my_dict.items0:
print("Key:", key, "Value:", value)

# Accessing keys only


print("\nAccessing keys only:")
for key in my_dict.keys():
print("Key:", key)

# Accessing values only


print("\nAccessing values only:")
for value in my_dict.values():
print("Value:", value)
-----------•11•---=-- =- ----------
Q2Q) Write a program to create a dictionary and find t he sum
of values

# Define two lists


listl = [1, 2, 3, 4, 5]
list2 = [3, 4, 5, 6, 7]

# Using set intersection to find common elements


common_elements = list(set(listl) & set(list2))

# Display the common elements


print("List 1:", listl)
print("List 2:", list2)
print("Common elements: ", common_elements)

You might also like