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

string operations

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

string operations

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Exercise – 5

-Maghizhvanban
-3122235002068

Class Diagram:
Question 1
1.Define a vector inheriting from standard list. Let the vector is restricted to having only integer
number in the list. Overload appropriate function and operator so that when any other type of
element is inserted the program raises an error.

2. Overload the operators ‘+’ & ‘–‘ to add and subtract two vectors respectively. Ex. V1 =[2,3,4], V2 =
[1], V+V2 =[3,3,4] V1-V2 = [1,3,4] {Odd Register numbered Students}

3. Overload the operators ‘+’ & ‘–‘ operator to result with the following definitions. Ex. V1 =[2,3,4],
V2 = [1,2], V+V2 =[1,2,3,4] – To merge two lists in ascending order without any duplicates. V-V2 =
[1,2,3] , where the new vector has items which are different in both the vectors. {Even Register
numbered Students}

4.Write a function called GetRatios(Vec1, Vec2) which reads the value of both the vectors in
appropriate index and generates the ratio vector Ratio[]. The Ratio[i] is calculated by Vec1[i]/Vec2[i].
Write the code for handling exceptions using try, except and raise in the following conditions:

(i) When there is a value ‘Zero’ at some index ‘x’ of Vec2, place ‘NaN’ in Ratio[x]

(ii) When the sizes of both the vectors are different

(iii) Create an user-defined exception object when the length of both the vectors are zero

CODE:
class v_0(Exception):
def __init__(self,err):
super.__init__(err)

class Vector(list):
def __init__(self,*value):
self.value = value
for _ in value:
if type(_) == int or type(_) == None:
pass
else:
raise Exception("Enter a integer value")
super().__init__(value)

def __add__(self, other):


values = [*(self.value + other.value)]
tem = []
for _ in values:
if _ not in tem:
tem.append(_)
values = tem
values.sort()
v = Vector(*values)
return v

def __sub__(self, other):


values = sorted(set(self).difference(other))
return Vector(*values)

def getratio(self,v1,v2):
if len(v1.value) != len(v2.value):
raise Exception('Enter a vector of same dimension')
if len(v1.value) == len(v2.value) == 0:
raise v_0("Both vector are zero")
tem = []
for i in v1:
for j in v2:
try:
tem.append(i/j)
break
except ZeroDivisionError:
tem.append(None)
v = Vector(*tem)
return v

Question2:
The constructor must assign the first name and last name of an employee. Define a function called
from_string() which gets a single string from the user, splits and assigns to the first and last name. For
example, if the string is ‘Seetha Raman’, the function should assign first name as Seetha and second
name as Raman and the function returns the object. Can you design from_string() as a class or
instance function? Justify your response. Demonstrate object creation by passing two strings as well
as one string.

Mention the significance of class and instance members:


In object-oriented programming, **class members** belong to the class itself and are
shared across all instances, while **instance members** are unique to each object. Instance
members (variables and methods) store individual object states and allow objects to behave
differently. Class members, on the other hand, are shared and used for data or behavior
common to all objects, helping to conserve memory by avoiding duplication. Instance
members are destroyed with the object, while class members persist as long as the class
exists. Together, they enable flexibility in data organization and behavior control within a
class.
CODE:
class Employee:
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name

@classmethod

def from_string(cls, name_string):


# Split the name_string into two parts
first_name, last_name = name_string.split()

# Create and return a new Employee object


return cls(first_name, last_name)

Question 3:
Explain the concept of Overriding and Operator Overloading concepts with the following example:

**Overriding** occurs when a subclass provides its own implementation of a method


already defined in its superclass, replacing the parent class behavior.

**Operator Overloading** allows built-in operators (like `+`, `-`, etc.) to be redefined for
user-defined classes, giving them new behavior based on the class's context.

For example, a subclass `Dog` might override a method `speak()` from its parent class `Animal` to
provide a different implementation. Similarly, you can overload the `+` operator in a class to define
how two objects of that class should be added together.

Implement the classes Movie() and MovieList() as described in the above figure. Override the
appropriate functions so that the MovieList is generated based on the genre assigned in the instance
variable when first object is created. For example, if the genre is defined as thriller, the list accepts
only thriller movies. When two lists are given as input, the list with more number of movies are
returned.
CODE:
class MovieList:
def __init__(self, genre):
self.genre = genre
self.movies = []

def add_movie(self, movie):


"""
Adds a movie to the list only if it matches the genre.
"""
if movie.genre == self.genre:
self.movies.append(movie)
else:
print(f"Cannot add movie '{movie.title}' to this list because it's not a {self.genre} movie.")

def __repr__(self):
# Format the movie list as 'MovieList(genre): title1 (genre), title2 (genre)'
movie_strs = [str(movie) for movie in self.movies]
return f"MovieList({self.genre}): {', '.join(movie_strs)}"

def __add__(self, other):


"""
Overloads the + operator to return the MovieList with more movies.
"""
if not isinstance(other, MovieList):
raise TypeError("Can only add another MovieList")
if len(self.movies) > len(other.movies):
return self
return other

OUTPUT:

You might also like