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

Lab Record

Uploaded by

Soni Supriya
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)
41 views

Lab Record

Uploaded by

Soni Supriya
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/ 126

LAB RECORD

Course code:19cse201

Submitted by

CH.EN.4CSE22055
SONI SUPRIYA

BACHELOR OF TECHNOLOGY
IN
COMPUTER SCIENCE AND ENGINEERING

AMRITA VISHWA VIDYAPEETHAM


AMRITA SCHOOL OF COMPUTING
CHENNAI
AMRITA VISHWA VIDYAPEETHAM

AMRITA SCHOOL OF COMPUTING, CHENNAI

BONAFIDE CERTIFICATE

This is to certify that the Lab Record work for 19CSE102 – Computer Programming Subject

submitted by CH.EN.U4CSE22055 Soni Supriya in “Computer Science and Engineering” is a

Bonafide record of the work carried out under my guidance and supervision at Amrita School of

Computing, Chennai.

Faculty name: Dr. A padmavathi Dr. S Sountharrajan


Assistant Professor Asso. Prof.& Program Head
Dept. of CSE Dept. of CSE

This Lab examination held on _________________

INTERNAL EXAMINER 1 INTERNAL EXAMINER 2


List Of Programs

s.no. date title


1. 19/07/23 Basic C++ programs
2. 26/07/23 Function overloading and overriding
3. 09/08/23 Operator overloading
4. 16/08/23 Inheritance and virtual function

5. 17/08/23 Pointers
6. 24/08/23 STL and templates
7. 13/09/23 Basic python programs
8. 20/09/23 Strings and built-in functions
in python
9. 27/09/23 Python functions
10. 4/10/23 Classes,objects,methods
11. 11/10/23 inheritance
12. 25/10/23 Data structures
Date:19/07/23 (week 1)
TITLE: Program using Built-in datatypes, arrays, struct, class.
Aim:(a) To write a C++ program that accepts a character as input and prints the
ascii value of the same character as output.

Algorithm:
1. start the program.
2. declare a variable to store the input character.
3. take the input of character from user.
4. convert the character to its ascii value by type conversion.
6.print the ascii value.
7. build and run the program.

Program:

Output:

Result:
Hence, the C++ program to accept a character and return its ASCII value was
successfully executed and the output was verified.
Aim:(b) To write a C++ program to declare a char, short, int, unsigned int,
unsigned long, float, double, long double datatypes variables and then print the
storage space reserved for those variables.
Algorithm:
1. start the program.
2. declare the variables of different data types.
3. print the storage space of each of the variables using the size of command.
4. Build and run the program.
Program:

Output:

Result: Hence, the program to print the storage size of various built-in datatypes was
successfully executed and verified.
Aim:(c) To write a C++ program that inputs five numbers and calculates the sum
and average of entered numbers using float array.
Algorithm:
1.start the program.
2.declare the variables to store the float values of array and the sum of the
numbers.
3. input the values from the user for the numbers
4.execute a for loop for taking the input and calculating the sum of the numbers.
5.print the sum and the average of the numbers.
6.built and run the program.
Program:

Output:

Result: Hence, the program to print the sum and the average of the numbers of a
float array was successfully executed and the output was verified.
Aim:(d) To declare a struct storing the following information related to students:
student_name, roll_num, marks. Create a struct object and store the values of the
object by taking input from the user. Add a function that displays the struct object
values.
Algorithm:
1. Start a program.
2. Create a struct named student and its properties.
3. Create an object for the stuct.
4. In the main function get the input of the values from the user.
5. Create a function of void data type and print the values of the properties
using the input values.
6. Build and run the program.
Program:

Output:
Result:
Hence, the program to create a struct with its given properties, getting the values
from the user and printing the values using another function was successfully
executed and the output was verified.
Aim:(e) To create the student class with the following data members:
student_name, roll_num, marks1, marks2. Take name, roll number, marks1 and
marks2 information from user. Calculate the mean value of marks and display
student_name, roll_num, mean mark values.
Algorithm:
1. Start the program.
2. Create a class named student and required data members.
3. Create a class object.
4. Get the input of the values from the user.
5. Print the values.
6. Built and run the program.
program
Output

Result:
Hence, the program to create a class with its properties and displaying the mean
of its marks along with student name and roll no was executed successfully and
the output was verified.
Date: 26/07/23 (week 2)

TITLE: Program using Getters and Setters,


Constructors, Friend Function, Function Overloading
1. function overloading
Aim:(a) to write a C++ program to calculate the area of a triangle, rectangle or
square based on the number of sides provided by the user using function
overloading
Algorithm:
1. Start
2. Create a function area for different shapes
3. Prompt user to enter number of sides
4. Calculate the area
5. Display the area
6. End
Program:
Output:

Result:
Hence, the above program was successfully implemented, and the output was
verified.
2. AIM: To create a class named worker with attributes id, name and
department. And implement methods to calculate the weekly wages.
Algorithm:
Code:

Output:

.
Result:

Hence, the above program was successfully implemented, and the output was
verified.
3. Aim: Create a class named 'complex' with two data members- real and imag and a
function to display the value which is in the form of 'a+ib'.

The class has three constructors which are :


1 - having no parameter - values of both real and imag are assigned zero.
2 - having two numbers as parameters
3 – Copy constructor
4 – Function to add two complex numbers.
ALGORITHM:
a. Start the program.
b. Define the complex class with private member variables n1, n2, n3, and n4.
c. Declare four member functions inside the class:
 complex(): Default constructor, initializes n1 and n2 to 0.
 complex(float a, float b): Parameterized constructor, initializes n1 and n2
with the given values a and b.
 complex(complex &o): Copy constructor, creates a new complex object
and copies the values of n1 and n2 from the existing complex object o.
 void put(): Display the complex number in the format n1 + n2i.
 void addtwo(int a, int b, int c, int d): Add two complex numbers and
display the result in the format (a + c) + (b + d)i.
d. In the main() function:
 Create a complex object c using the default constructor. This initializes n1
and n2 to 0. Display the complex number using the put() function.
 Create a complex object c1 using the parameterized constructor with
values 1 and 2.3. Display the complex number using the put() function.
 Create a complex object c5 using the parameterized constructor with
values 5 and 6.
 Create a complex object c3 using the copy constructor and passing c5 as
an argument. Display the complex number using the put() function.
 Create a complex object c4 using the default constructor. Call the
addtwo(7, 8, 9, 10) member function on c4 to add two complex numbers
(7+8i) and (9+10i) and display the result.
e. End the program.
CODE:
OUTPUT:

Result: Therefore, the above c++ code has been demonstrated successfully

4. Aim: Create a class 'Student' with three data members which are name, age and
address. The constructor of the class assigns default values to name as "unknown",
age as '0' and address as "not available". It has two functions with the same name
'setInfo'. First function has two parameters for name and age and assigns the same
whereas the second function takes has three parameters which are assigned to
name, age and address respectively. Print the name, age and address of 10 students.
ALGORITHM:

a. Start the program.


b. Define the Student class with private member variables age, name, and address.
c. Declare three member functions inside the Student class:
● Student(): This is the default constructor, which initializes age to 0, name to
"unknown", and address to "not available".
● void setinfo(string name1, int age1): This function sets the name and age of
the student object with the provided values name1 and age1.
● void setinfo(string name1, int age1, string address1): This function sets the
name, age, and address of the student object with the provided values name1,
age1, and address1.
● void disp(): This function displays the details of the student, including their
name, age, and address.
d. In the main() function:
● Create an array students of Student objects with size 10.
● Set the details of each student using the setinfo() function with the provided
name, age, and address for each student.
● Iterate through the array of students using a for loop from 0 to 9:
● Display the details of each student using the disp() function.
e. End the program.
CODE:
OUTPUT:
Result: Therefore, the above c++ code has been demonstrated successfully
5. Aim: Write a program in C++ to print the product of two numbers using friend
function.
ALGORITHM:
a. Start the program.
b. Define a sum class with private member variables n1 and n2.
c. Declare a friend function int addtwo(sum) inside the sum class. This function will be
able to access the private member variables of the sum class.
d. Define the int addtwo(int n1, int n2) function outside the sum class. This function
calculates the sum of two integers n1 and n2 and returns the result.
e. In the main() function:

● Declare two integer variables n1 and n2 to store user input for the first and
second numbers.

● Prompt the user to enter the first number and store it in n1.

● Prompt the user to enter the second number and store it in n2.

● Call the addtwo(n1, n2) function to calculate the sum of the two numbers and
display the result.
f. End the program.
CODE:

OUTPUT:
Result: Therefore, the above c++ code has been demonstrated successfully.
Date: 09/09/23 (week 3)

TITLE: Program Using Operator Overloading and Static


Members

1. Aim: Create a class called Distance with private members feet and inches.
(i) Use parameterized constructor to read the value of feet and inches.
(ii) use member function display () to display the read value.
(iii) Use operator fn + to add two distances using friend function.

Algorithm:
a. Start
b. Define a class "Distance" with private members "feet" and "inches".
c. Declare a constructor for the class "Distance" that initializes the "feet" and
"inches" members.
d. Define a member function "disp()" within the "Distance" class to display the
values of "feet" and "inches".
e. Declare a friend function "operator + " to overload the addition operator for the
"Distance" class.
f. Implement the "operator + " function to add two Distance objects and return the
result as a new Distance object.
g. In the "main" function: a. Create two "Distance" objects, "d1" and "d2", with
initial values. b. Display the values of "d1" and "d2" using the "disp()" member
function. c. Add "d1" and "d2" using the overloaded "+" operator and store the
result in "d3". d. Display the values of "d3" using the "disp()" member function.
h. End

Code:
OUTPUT:
Result: Therefore, the above c++ code has been demonstrated successfully

b) Aim: Get two strings. Check whether entered strings are equal using operator
overloading using member function.

Algorithm:
a. Start
b. Define a class String with a private member char str[100].
c. Declare the getdata() function in the class String to read input string from the user
using gets() (Note: gets() is deprecated and should be replaced with fgets()).
d. Overload the == operator in the String class to compare two String objects.
e. In the main() function:
 Create two objects of the String class, s1 and s2.
 Output a message asking the user to enter the first string.
 Call the getdata() function for s1 to read the first string from the user.
 Output a message asking the user to enter the second string.
 Call the getdata() function for s2 to read the second string from the user.
 Compare the two strings using the overloaded == operator.
 If the strings are equal, output "The two given strings are equal."
 If the strings are not equal, output "The two given strings are not equal."
a. End

Code:
Output:

Result: Therefore, the above c++ code has been demonstrated successfully
c. Aim: Create a class box having length, breadth and height as private data members and
count as static data member.
a) The class uses a constant member function getvolume() to return the product of length,
breadth and height.
b) The class uses static member function to return the count.

Algorithm:
a. Start
b. Define a class Box.
c. Inside the class Box, declare the private member variables length, breadth, and
height of type float, and a static private member variable count1 of type int.
d. Declare the public member functions: 4.1. setvalues(float l, float b, float h): Set the
values of length, breadth, and height to the given parameters l, b, and h. 4.2.
getvolume(): Calculate and return the volume of the box using the formula length *
breadth * height. 4.3. static void setcount(float c): Set the value of the static
member variable count1 to the given parameter c. 4.4. static float getcount():
Return the value of the static member variable count1.
e. Define and initialize the static member variable count1 outside the class Box.
f. In the main() function:
 Create an object b of the Box class.
 Set the values of length, breadth, and height for the box using the
setvalues() function.
 Calculate and output the volume of the box using the getvolume() function.
 Set the value of the static member variable count1 to 3 using the setcount()
function.
 Output the value of the static member variable count1 using the getcount()
function.
b. End

Code:

Output:
Result: Therefore, the above c++ code has been demonstrated successfully.
Date: 16/09/23 (week 4)

TITLE: Program Using Inheritance, Virtual Function


a. Aim: Create a class named Vehicle with two data member named mileage and price.
Create its subclass Car with data members to store ownership cost, warranty (by years),
seating capacity and fuel type (diesel or petrol). store and print the information of a car
(ownership cost, warranty, seating capacity, fuel type, mileage, and price)

Algorithm:
a. Class Definition:
 Define a class Vehicle with data members mileage and price.
 Define a constructor to initialize mileage and price.
 Define a member function displayInfo() to print mileage and price.
b. Inheritance:

 Define a class Car that inherits from Vehicle.


 Add additional data members: ownershipCost, warrantyYears,
seatingCapacity, and fuelType.
c. Car Class Constructor:
 Define a constructor for the Car class to initialize the inherited
members from Vehicle as well as the new members.
d. Display Information:
 Override the displayInfo() function in the Car class to also print
ownershipCost, warrantyYears, seatingCapacity, and fuelType.
e. Main Function:
 In the main function:
 Create an instance of the Car class with specific values for its
parameters.
 Call the displayInfo() function for the car object to print out all the
information.
f. Output:
 When the program is executed, it will display information about the
car including mileage, price, ownership cost, warranty years, seating
capacity, and fuel type.
Code:

Output:

Result: Therefore, the above c++ code has been demonstrated successfully
2. Aim: We want to calculate the total marks of each student of a class in Physics,
Chemistry and Mathematics and the average marks of the class. The number of
students in the class is entered by the user. Create a class named Marks with data
members for roll number, name, and marks. Create three other classes inheriting
the Marks class, namely Physics, Chemistry and Mathematics, which are used to
define marks in individual subject of each student. The roll number of each student
will be generated automatically.
Algorithm:
a. Class Marks:
 Define a class Marks with data members rollNumber, name, and marks.
 Create a static variable rollNumberCounter to keep track of the roll
numbers.
 Define a constructor to initialize name and marks and automatically
generate a unique rollNumber.
 Define a member function displayInfo() to print rollNumber, name, and
marks.
b. Class Physics, Chemistry, Mathematics:
 Define three classes Physics, Chemistry, and Mathematics, each inheriting
from Marks.
c. Main Function:
d. In the main function:
 Ask the user to enter the number of students (numStudents).
 For each student, prompt for their name, Physics, Chemistry, and
Mathematics marks.
 Create objects of Physics, Chemistry, and Mathematics for each student
with the entered data.
 Display the information for each student.
e. Roll Number Counter:
 The rollNumberCounter is static and is incremented every time a new
object of class Marks is created, ensuring a unique roll number for each
student.
Code:
Output:

Result: Therefore, the above c++ code has been demonstrated successfully.
3. Aim: Create a class named Shape with a function that prints "This is a shape".
Create another class named Polygon inheriting the Shape class with the same
function that prints "Polygon is a shape". Create two other classes named Rectangle
and Triangle having the same function which prints "Rectangle is a polygon" and
"Triangle is a polygon" respectively. Again, make another class named Square
having the same function which prints "Square is a rectangle".

Algorithm:

a. Class Shape:
 Define a class Shape.
 Create a member function printShape() that prints "This is a shape".
b. Class Polygon (Inherits from Shape):
 Define a class Polygon inheriting from Shape.
 Override the printShape() function to print "Polygon is a shape".
c. Class Rectangle (Inherits from Polygon):
 Define a class Rectangle inheriting from Polygon.
 Override the printShape() function to print "Rectangle is a polygon".
d. Class Triangle (Inherits from Polygon):
 Define a class Triangle inheriting from Polygon.
 Override the printShape() function to print "Triangle is a polygon".
e. Class Square (Inherits from Rectangle):
 Define a class Square inheriting from Rectangle.
 Override the printShape() function to print "Square is a rectangle".
f. Main Function:
 In the main function:
 Create objects of classes Shape, Polygon, Rectangle, Triangle, and Square.
 Call the printShape() function for each object.

Code:
Output:
Result: Therefore, the above c++ code has been demonstrated successfully
Date: 20/09/23 (week 5)

TITLE: Program on Pointers


1.Aim: Write a C++ program to print the address and value of the variable.
Algorithm:
a. Variable Declaration
 Declare an integer variable num and initialize it with the value 10.
b. Print Address and Value:
 Use cout to print the message "Address of variable 'num': ".
 Use the & operator to get the address of the variable num and print it.
 Use cout to Variable Decalaration:
 print the message "Value of variable 'num': ".
 Print the value of the variable num.
c. Return Statement:
 Use return 0; to indicate successful execution of the program.

Code:

Output:
Result: Therefore, the above c++ code has been demonstrated successfully
2. Aim: Write a C++ program to find the smallest of three numbers using pointers.

Algorithm:
a. Function findSmallest:
 Define a function findSmallest that takes three pointers to integers as
arguments: ptr1, ptr2, and ptr3.
 Initialize a variable min with the value pointed to by ptr1.
 Compare the values pointed to by ptr2 and ptr3 with min. If either is smaller,
update min accordingly.
 Return the value of min.
b. Main Function:
 Declare three integer variables num1, num2, and num3.
 Prompt the user to enter three numbers and store them in the respective
variables.
 Define three pointers ptr1, ptr2, and ptr3 and assign them the addresses of
num1, num2, and num3 respectively.
 Call the function findSmallest with the pointers as arguments and store the
result in the variable smallest.
Print the smallest number.
c. Return Statement:
 Use return 0; to indicate successful execution of the program.

Code:
Output:

Result: Therefore, the above c++ code has been demonstrated successfully

3. Aim: Given String is AmritA. Convert uppercase to lowercase and vice versa using
pointers
Algorithm:
a. Function convertCase:
 Define a function convertCase that takes a pointer to a character array (char*
str) as an argument.
 Use a while loop to iterate through each character of the string until the null
terminator \0 is encountered.
 Inside the loop:
 If the character is a lowercase letter (*str >= 'a' && *str <= 'z'), convert it to
uppercase using toupper.
 If the character is an uppercase letter (*str >= 'A' && *str <= 'Z'), convert it to
lowercase using tolower.
 Increment the pointer to move to the next character.
b. Main Function:
 Declare a character array str and initialize it with the string "AmritA".
 Print the original string.
 Call the convertCase function with str as the argument to convert the case of
the characters.
 Print the modified string.
 Use return 0; to indicate successful execution of the program.

Code:

Output:
Result: Therefore, the above c++ code has been demonstrated successfully.

4. Aim: Write a C++ program to print a number and name (Entered using Keyboard)
using this pointer.
Algorithm:
a. Variable Declaration:
 Declare an integer variable number and a string variable name.
b. Pointer Declaration:
 Declare pointers ptrNumber and ptrName of type int* and string*
respectively.
 Assign the addresses of number and name to ptrNumber and ptrName.
c. Input:
 Use cin to prompt the user to enter a number.
 Store the input in the location pointed to by ptrNumber.
d. Clear Buffer:
 Use cin.ignore() to clear the newline character from the buffer.
e. Input Name:
 Use getline(cin, *ptrName) to prompt the user to enter a name.
 Store the input in the location pointed to by ptrName.
f. Output:
 Print the number and name using cout and the dereferenced pointers.
g. Return Statement:
 Use return 0; to indicate successful execution of the program.

Code:

Output:
Result: Therefore, the above c++ code has been demonstrated successfully

5. Aim: Write a C++ program to print the elements of an array using pointer.
Algorithm:
a. Function printArray:
 Define a function printArray that takes a pointer to an integer array (int* arr)
and the size of the array (int size) as arguments.
 Use a for loop to iterate through each element of the array.
 Print the value at the memory location pointed to by arr + i.
b. Main Function:
 Declare a constant SIZE and an integer array numbers with 5 elements.
 Initialize the array with values {1, 2, 3, 4, 5}.
 Call the printArray function with numbers and SIZE as arguments to print the
elements of the array.
c. Return Statement:
 Use return 0; to indicate successful execution of the program.

Code:

Output:

Result: Therefore, the above c++ code has been demonstrated successfully
6. Aim: Write a function which will take pointer and display the number on screen.
Take number from user and print it on screen using that function. ( Pointer to
Function)

Algorithm:
a. Function displayNumber:
 Define a function displayNumber that takes a pointer to an integer (int* ptr) as an
argument.
 Inside the function, use cout to print the number pointed to by ptr.
b. Main Function:
 Declare an integer variable number.
 Prompt the user to enter a number and store it in number.
 Define a pointer ptr and assign it the address of number.
 Call the function displayNumber with ptr as the argument.
c. Return Statement:
 Use return 0; to indicate successful execution of the program.

Code:

Output:
Result: Therefore, the above c++ code has been demonstrated successfully

Date: 27/09/23 (week 6)


TITLE: Program on Function Templates, Class Templates, STL
1 .Aim: Write a function template to find the average elements of an array. Pass the
entire array and its size as an argument to a function.

Algorithm:
a. Function Template findAverage:
 Define a function template findAverage that takes an array arr of type T and its size
size as arguments.
 Initialize a variable sum of type T to zero.
 Use a for loop to iterate through each element of the array and accumulate their sum
in sum.
 Return the average as sum / size.
b. Main Function:
 Declare two arrays intArray and doubleArray.
 Determine their sizes using sizeof and division by the size of the respective data
types.
 Call findAverage with intArray and doubleArray along with their respective sizes.
 Print the calculated averages.
 Use return 0; to indicate successful execution of the program.

Code:

Output:
Result: Therefore, the above c++ code has been demonstrated successfully

1. Aim: Write a function template to sort the elements using bubble sort.
Algorithm:
a. Function Template bubbleSort:
 Define a function template bubbleSort that takes an array arr of type T and its size
size as arguments.
 Use nested for loops to iterate through the array using the bubble sort algorithm.
 Compare adjacent elements and swap them if they are in the wrong order.
 Function Template displayArray:
 Define another function template displayArray that takes an array arr of type T and
its size size as arguments.
 Use a loop to iterate through the array and print its elements.
b. Main Function:
 Declare two arrays intArray and doubleArray.
 Determine their sizes using sizeof and division by the size of the respective data
types.
 Print the arrays before sorting.
 Call bubbleSort with intArray and doubleArray along with their respective sizes.
 Print the arrays after sorting.
c. Return Statement:
 Use return 0; to indicate successful execution of the program.

Code:
Output:
Result: Therefore, the above c++ code has been demonstrated successfully

2. Aim: Write a C++ program to implement the queue concept using class templates.
Algorithm:
a. Class Template Queue:
 Define a class template Queue that takes a generic type T.
 Include private data members arr (an array to store elements), front (front pointer),
rear (rear pointer), and capacity (maximum capacity of the queue).
b. Constructor Queue:
 Initialize capacity with the given size, create a dynamic array of type T, and set front
and rear to -1.
c. Destructor ~Queue:
 Deallocate the memory allocated for the dynamic array.
d. Function isEmpty:
 Returns true if both front and rear are -1.
e. Function isFull:
 Returns true if (rear + 1) % capacity is equal to front.
f. Function enqueue:
 Adds an element to the queue if it is not full. Adjusts front and rear pointers
accordingly.
g. Function dequeue:
 Removes an element from the queue if it is not empty. Adjusts front and rear
pointers accordingly.
h. Function peek:
 Returns the element at the front of the queue without removing it.
i. Main Function:
 Creates an instance of Queue with int as the generic type.
 Enqueues elements, peeks at the front element, and dequeues an element.

Code:
Output:

Result: Therefore, the above c++ code has been demonstrated successfully
3. Aim: You are given integers. Sort the integers and print the sorted order. Store
the integers in a vector. Vectors are sequence containers representing arrays that
can change in size.

Algorithm:
a. Include Header Files:
 Include necessary header files:
 iostream for input/output operations.
 vector for using vectors from the STL.
 algorithm for using the std::sort function.
b. Main Function:
 Declare an integer variable n to store the number of integers.
 Prompt the user to enter the number of integers.
 Create a vector integers of size n to store the input integers.
c. Input Integers:
 Prompt the user to enter n integers and store them in the vector integers.
d. Sort the Vector:
 Use std::sort to sort the elements in the vector in ascending order.
e. Print Sorted Order:
 Print the sorted elements in the vector.

Code:
Output:

Result: Therefore, the above c++ code has been demonstrated successfully
4. Aim: Write an STL program to reverse the elements of linked list.

Algorithm:
a. Include Header Files:
 Include necessary header files:
 iostream for input/output operations.
 list for using linked lists from the STL.
b. Main Function:
 Create a linked list linkedList to store the elements.
c. Input Elements:
 Prompt the user to enter the number of elements (n).
 Prompt the user to enter n elements and push them into the linked list.
d. Reverse the List:
 Use the reverse function provided by the linked list to reverse its elements.
e. Print Reversed List:
 Traverse the linked list and print the reversed elements.

Code:
Output:

Result: Therefore, the above c++ code has been demonstrated successfully
Date: 13/09/23 (week 7)
TITLE: Program on Python Basics, Control Statements
1 . Aim: Calculate the area of a triangle using Heron’s formula
Algorithm:
1. Start the program
2. Get the input of the side
3. Calculate the semi-perimeter.
4. Using sqrt from math module and calculate the area using the formula.
5. Print output.
Code:

Output:

Result:
Hence, the above program was executed successfully, and the output was also
verified.
2. Aim: Compute the area of a right-angled triangle with non-hypotenuse sides
as ‘a’ and ‘b’.

Algorithm:
1. Start the program
2. Get the input of the side
3. Calculate the area using the formula.
4. Print the output.
5. End
Code:

Output:

Result:
Hence, the above program was executed successfully, and the output was also
verified.
3. Aim:x = 10 if (x>0): x = x+1 print(x)
Task: Run the program for x = -10. Rewrite the program so that x is printed.

Algorithm:
1. Start
2. Set x value as –10.
3. In the if block if we remove the intendentaion from the print statement
4. Prints the value of x as –10.
5. End.

Code:

Output:

Result:
Hence, the above program was executed successfully, and the output was also
verified.
4 . Aim: Enter a number and then calculate the sum of its digits (While Loop).
Algorithm:
1. Start.
2. Input the number
3. Set the sum as 0 .
4. Start the while loop
5. Iterate the loop add the last digit of num and removing the last digit from
num
6. end
Code:

Output:

Result:
Hence, the above program was executed successfully, and the output was also
verified.
5 . Aim: Generate calendar of a month given the start_day and number of days in that
month use for loop and Range.

Algorithm:
a. Define the function generate_calendar(start_day, total_days).
b. Define the names of the days of the week
c. The variable days_of_week is a list containing the names of the days.
d. Print the header with day names
e. The day names (Su, Mo, Tu, ...) are printed as the header.
f. Calculate the position of the first day
g. The position of the first day is determined by finding its index in the days_of_week
list.
h. Initialize the day counter
i. Print the first row with empty spaces before the first day
j. A loop is used to print empty spaces before the first day, based on the start_position.
k. Loop through the days and print the calendar
l. After printing a day, we check if a new line needs to be started for the next week.
m. Print a newline at the end

Code:

Output:
Result: Therefore, the above python code has been demonstrated successfully

6. Aim: Find LCM of two numbers ( do while loop )

Algorithm:
a. Define the function find_lcm(a, b)
b. This function takes two arguments a and b, which are the two numbers for which we
want to find the LCM.
c. Find the greater number
d. Determine the greater number among a and b and store it in the variable greater.
e. Initialize the LCM
f. Start an infinite loop
g. We use a while True loop, which will run indefinitely until explicitly terminated.
h. Check if lcm is a multiple of both a and b
i. If lcm is divisible by both a and b (i.e., lcm % a == 0 and lcm % b == 0), it means lcm
is the LCM of a and b, and we can exit the loop.
j. Increment lcm by the value of greater
k. If lcm is not a multiple of both a and b, we increment it by the value of greater to
continue checking.
l. Return the LCM
m. Print the result
Code:

Output:
7 .Aim: If a language is Javascript you can become a web developer, if a language is python,
you become a data scientis, if a language is PHP, you can become a backend developer, if a
language is Java you can become a mobile app developer , if a language is solidity , you can
become a blockchain developer.
I. Write a python program using if-elseif-else

Algorithm:
a. Define the function get_career_if(language)
b. This function takes one argument, language, which is the programming language
being evaluated.
c. Using if-elif-else statements
d. The function uses if-elif-else statements to determine the career based on the
provided language.
e. If language matches a known programming language, the corresponding career is
returned. Otherwise, the default case returns "Unknown Career".
f. In this part, an example is provided where language is set to 'Python'. The function
is called, and the result is printed.
g. Print the result

Code:

Output:
8 .AIM :Write a python program using switch-case
Algorithm:
a. Define the function get_career_switch(language)
b. This function takes one argument, language, which is the programming language
being evaluated.
c. Define a dictionary careers
d. The keys are the programming languages, and the values are the corresponding
careers.
e. Return the value using get method
f. The function uses the get method of dictionaries to return the career based on the
provided language. If the language is not found, it returns the default value, which is
'Unknown Career'.
g. In this part, an example is provided where language is set to 'Java'. The function is
called, and the result is printed.
h. Print the result

Code:

Output:

Result: Therefore, the above python code has been demonstrated successfully
Date: 13/09/23 (week 8)
TITLE: Program on Python Data Structures.
1 .Aim: 'tomato’, 'to' are given strings s1 and s2 , count the occurrence of string s2 in
s1

Algorithm:
a. define the function count_occurrences(s1, s2)
b. This function takes two arguments, s1 and s2, which are the strings to be evaluated.
c. Use the count () method
d. The count () method is applied to s1 with s2 as an argument. This method returns
the number of non-overlapping occurrences of s2 in s1.
e. Return the number of occurrences
f. The function returns the result obtained from the count () method.
g. Print the result

Code:

Output:

Result: Therefore, the above python code has been demonstrated successfully
2 .Aim: The given input is ke@##123KEY, Output: ke123KEY. Remove all special
characters other than digits and characters

Algorithm:
a. Define the function remove_special_characters(input_string)
b. This function takes one argument, input_string, which is the input string to be
processed.
c. The list comprehension iterates through each character in input_string.
d. Check if the character is alphanumeric or a space
e. For each character, it checks if it is alphanumeric (a letter or a digit) or a space using
the isalnum() method.
f. The characters that meet the condition are joined together to form the result string.
g. Return the result
h. Print the result

Code:

Output:

Result: Therefore, the above python code has been demonstrated successfully
3 .Aim: Input: match output: maatttcccchhhhh
Algorithm:
a. Define the function duplicate_characters(input_string)
b. This function takes one argument, input_string, which is the input string to be
processed.
c. Use a list comprehension
d. The list comprehension iterates through each character in input_string.
e. Duplicate and repeat the character
f. For each character, it duplicates it using the * operator and repeats it three times.
g. Join the characters
h. The duplicated characters are joined together to form the result string.
i. Return the result
j. The function returns the modified string.
k. Print the result

Code:

Output:

Result: Therefore, the above python code has been demonstrated successfully
4 . Aim: Input: calculate Output: cate (first two characters and last two characters)

Algorithm:
a. Define the function extract_characters(input_string)
b. Use string slicing
c. The slicing notation input_string[:2] extracts the first two characters of the input
string.
d. The slicing notation input_string[-2:] extracts the last two characters of the input
string.
e. Concatenate the substrings
f. The first two and last two characters are concatenated using the + operator.
g. Return the result
h. In this part, an example is provided where input_string is "calculate". The function is
called, and the result is printed.
i. Print the result

code:

Output:

Result: Therefore, the above python code has been demonstrated successfully

5 . Aim: Given two tuples t1=(11,3), t2=(15,70) . Find all the pair of combinations of
tuple. Output: (11,15),(11,70), (3,15),(3,70),(15,11),(15,3),(70,11),(70,3)
Algorithm:
a. Define the function find_combinations(t1, t2)
b. This function takes two arguments, t1 and t2, which are the input tuples.
c. The list comprehension iterates through each element in t1 and t2.
d. For each combination of elements, a tuple (x, y) is created, where x is from t1 and y
is from t2.
e. Return the list of combinations
f. The function returns the list of combinations.
g. In this part, the given tuples t1 and t2 are specified.
h. Call the function
i. The function is called with the provided tuples.
j. Print the result

code:
Output:

Result: Therefore, the above python code has been demonstrated successfully

6 . Aim: Convert tuple of list to tuple Input : ( [10,50,60] , [40,65]) Output :


(10,50,60,40,65)
Algorithm:
a. Define the function convert_tuple_of_lists(input_tuple)
b. This function takes one argument, input_tuple, which is the tuple of lists to be
processed.
c. Initialize an empty list result_list
d. Iterate through each sublist in the input tuple
e. Use a for loop to go through each sublist in the input tuple.
f. Extend the result_list with the elements from the sublist
g. The extend method is used to add all elements from the sublist to the result_list.
h. Once all elements have been added, the list is converted to a tuple using the tuple
function.The function returns the resulting tuple.
i. The function is called with the provided input tuple.
j. Print the result

code:

Output:

7 . Aim: Write a python script to merge two dictionaries

Algorithm:
a. Define the function merge_dicts(dict1, dict2)
b. This function takes two dictionaries, dict1 and dict2, as arguments.
c. The line merged_dict = dict1.copy() creates a copy of dict1 called
merged_dict.
d. Update merged_dict with the contents of dict2.The update () method is
used to merge the contents of dict2 into merged_dict.
e. Return the merged dictionary
f. The function returns the merged dictionary.
g. Print the result

code:

Output:

Result: Therefore, the above python code has been demonstrated successfully

8 . Aim: Combine two dictionaries adding values for common keys.


Input: D1= {‘a’:100, ‘b’:200, ‘c’:300, ‘d’:400} D2 = { ‘a’:50 , ‘b’:20 , ‘c’ : 100 }
Output: {‘a’:150, ‘b’:220,’c’:400, ‘d’:400}

Algorithm:
a. Define the function combine_dictionaries(d1, d2)
b. This function takes two dictionaries, d1 and d2, as arguments.
c. Initialize a new dictionary combined_dict
d. This dictionary will hold the combined values.
e. For each key in d1, check if it also exists in d2.
f. If the key exists in both dictionaries, add their values together and assign it to the
key in combined_dict.
g. Add keys unique to d1 and d2
h. If a key exists only in d1, add it to combined_dict.
i. Iterate through the keys in d2 and add any keys that are unique to d2.
j. Return the combined dictionary
k. The function returns the combined_dict.
l. In this part, the given dictionaries D1 and D2 are specified.
m. Print the result

code:

Output:

Result: Therefore, the above python code has been demonstrated successfully

9 . Aim: Write a program that creates a list [ ‘a’, ‘b’, ‘c’] then create a tuple from that list.
Now do the opposite. That is create the tuple (‘a’,’b’,’c’) and then create a list from it.
Algorithm:
a. Create a list and convert it to a tuple
b. list_to_tuple = ['a', 'b', 'c']: This creates a list with elements 'a', 'b', and 'c'.
c. tuple_from_list = tuple(list_to_tuple): This converts the list to a tuple.
d. Create a tuple and convert it to a list
e. tuple_to_list = ('a', 'b', 'c'): This creates a tuple with elements 'a', 'b', and 'c'.
f. list_from_tuple = list(tuple_to_list): This converts the tuple to a list.
g. Print the results
h. Print (f"List to Tuple: {tuple_from_list}"): This prints the tuple created from the list.
i. Print (f"Tuple to List: {list_from_tuple}"): This prints the list created from the tuple.

code:

Output:

10 .Aim: Create a dictionary of products purchased and their MRPs. Calculate the bill and
display to the customer.

Algorithm:
a. Define the function calculate_bill(products, prices, quantities)
b. This function takes three lists as arguments: products, prices, and quantities.
c. itemized_bill is a dictionary that will store the total cost of each product.
d. Iterate through the products, prices, and quantities
e. Use a loop to iterate through the indices of the lists.
f. Multiply the price of the product by its quantity to get the total cost.
g. Store the total cost in the itemized_bill dictionary with the product as the key.
h. Return the total bill and itemized bill
i. The function returns both the total bill and the itemized bill as a dictionary.
j. Given products, prices, and quantities
k. In this part, the lists of products, prices, and quantities are specified.Call the function
l. Display the bill to the customer
m. The itemized bill is printed first, showing the cost of each product. Then, the total
bill is displayed.

code:

Output:

Result: Therefore, the above python code has been demonstrated successfully
11. Aim: Write a program that prints the maximum and minimum value in a dictionary.

Algorithm:
a. Define the function find_max_min(dictionary)
b. This function takes a dictionary as an argument.
c. Check if the dictionary is empty
d. If the dictionary is empty, return None for both maximum and minimum values.
e. Use the max() and min() functions to find the maximum and minimum values in the
dictionary.
f. Return the maximum and minimum values
g. The function returns both the maximum and minimum values.
h. In this part, the given dictionary sample_dict is specified.
i. The function is called with the provided dictionary.
j. If the dictionary is not empty, the maximum and minimum values are printed.
Otherwise, a message indicating that the dictionary is empty is printed.

code:

Output:

Result: Therefore, the above python code has been demonstrated successfully

12 . Aim: Write the command to print “hello world” as “Hello World”


Algorithm:
a. Use the print function
b. print("hello world".title()): This line prints the string "hello world" after converting
it to title case.
c. .title() method
d. The .title() method converts the first character of each word to uppercase and the
remaining characters to lowercase.

code:

Output:

Result: Therefore, the above python code has been demonstrated successfully

13. Aim: Write the command to print “hElLo WoRlD” as “HeLlO wOrLd”

Algorithm:
a. Use the print function
b. Print ("hElLo WoRlD".swapcase()): This line prints the string "hElLo WoRlD" after
swapping the case of each character.
c. .swapcase() method
d. The .swapcas () method swaps the case of each character in the string.

Code:

Output:

Result: Therefore, the above python code has been demonstrated successfully

14 .Aim: Write the command to print “hello world” as “Hello Friends”

Algorithm:
a. Use the print function
b. Print ("hello world".replace("world", "Friends").capitalize()): This line prints the
string "hello world" after replacing "world" with "Friends" and capitalizing the first
letter.
c. .replace() method
d. The .replace() method is used to replace occurrences of a specified substring with
another string.
e. .capitalize() method
f. The .capitalize() method capitalizes the first letter of the string.

code:

Output:

Result: Therefore, the above python code has been demonstrated successfully

15 .Aim: Write a program that encrypts a message by adding a key value to every
character. [Note : key vaue=3] , Input : hell Output: khoor

Algorithm:
a. Define the function encrypt_message(message, key)
b. This function takes two arguments: message, the input message, and key, the value
by which each character is shifted.
c. Initialize an empty string encrypted_message
d. char.isalpha(): This checks if the character is an alphabet.
e. ascii_value = ord(char): This gets the ASCII value of the character.
f. shifted_value = ascii_value + key: This calculates the shifted ASCII value.
g. Handle uppercase and lowercase characters
h. Append the encrypted character to the result
i. encrypted_message += chr(shifted_value): This appends the encrypted character to
the result.
j. Return the encrypted message
k. The function returns the encrypted message.
l. The function is called with the provided message and key.
m. Print the result

code:

Output:

Result: Therefore, the above python code has been demonstrated successfully.
Date: 27/09/23 (week 9)
TITLE: Python Functions
1 .Aim: Write a program to find the product of two integers using function
Algorithm:
a. Define the function multiply(x, y)
b. This function takes two arguments, x and y, which are the two integers to be
multiplied.
c. product = x * y: This line computes the product of x and y.
d. return product: The function returns the calculated product.
e. In this part, the integers num1 and num2 are specified.
f. result = multiply(num1, num2): This line calls the multiply function with the
provided integers and stores the result.
g. Print (f"The product of {num1} and {num2} is: {result}"): This line prints the result.

Code:

Output:

Result: Therefore, the above python code has been demonstrated successfully
2 .Aim: Write a program to swap two strings using function

Algorithm:
a. Define the function swap_strings(str1, str2)
b. This function takes two arguments, str1 and str2, which are the strings to be
swapped.
c. temp = str1: This line stores the value of str1 in a temporary variable temp.
d. str1 = str2: This line assigns the value of str2 to str1.
e. str2 = temp: This line assigns the value of temp to str2.
f. The function returns the two swapped strings.
g. In this part, the strings string1 and string2 are specified.
h. string1, string2 = swap_strings(string1, string2): This line calls the swap_strings
function with the provided strings and stores the result.
i. Print (f"String 1 after swapping: {string1}"): This line prints the value of string1
after swapping.
j. Print (f"String 2 after swapping: {string2}"): This line prints the value of string2
after swapping.

Code:

Output:
Result: Therefore, the above python code has been demonstrated successfully

3 .Aim: Write a function “perfect ()” that determines if parameter number is a perfect
number. Use this function in a program that determines and prints all the perfect numbers
between 1 and 1000. [An integer number is said to be “perfect number” if its factors,
including 1(but not the number itself), sum to the number. E.g., 6 is a perfect number
because 6=1+2+3].

Algorithm:
a. Define the function perfect(number)
b. divisors = [i for i in range(1, number) if number % i == 0]: This list comprehension
generates a list of divisors for the given number.
c. sum(divisors) == number: This checks if the sum of the divisors is equal to the
number itself.
d. perfect_numbers = [num for num in range(2, 1001) if perfect(num)]: This list
comprehension generates a list of perfect numbers between 2 and 1000.
e. Print ("Perfect numbers between 1 and 1000:"): This line prints a message
indicating the range of numbers.
f. for num in perfect_numbers: print(num): This loop iterates through the list of
perfect numbers and prints each one.

Code:

Output:

Result: Therefore, the above python code has been demonstrated successfully
4 .Aim: Write a program to find the length of the string "refrigerator" without using Len
function

Algorithm:
a. Define the function find_length(string)
b. This function takes a string as an argument.
c. length = 0: This variable will be used to keep track of the length of the string.
d. Use a loop to go through each character in the string.
e. For each character, increment the length by 1.
f. return length: The function returns the calculated length of the string.
g. In this part, the string "refrigerator" is specified.
h. length = find_length(input_string): This line calls the find_length function with the
provided string and stores the result.
i. Print (f"The length of the string is: {length}"): This line prints the length of the
string.

Code:

Output:

Result: Therefore, the above python code has been demonstrated successfully
5 Aim: Write a program to make a new string with all the consonants deleted from
the string "Hello, have a good day".

Algorithm:
a. Define a function named remove_consonants that takes an input_string as an
argument.
b. Create a string vowels containing all lowercase and uppercase vowels.
c. Initialize an empty string result_string to store the final output.
d. Iterate through each character char in the input_string.
e. Check if char is an alphabetic character and not a vowel.
f. If it meets the criteria, append char to the result_string.
g. Return the result_string.

Code:

Output:

Result: Therefore, the above python code has been demonstrated successfully

6 .Aim: Write a program that finds sum of all even numbers in a set using function.
Algorithm:
a. Define a function named sum_even_numbers that takes a set number_set as an
argument.
b. Initialize a variable even_sum to store the sum of even numbers and set it to 0.
c. Iterate through each element num in number_set.
d. Check if num is even by using the modulus operator % with 2. If num % 2 equals 0,
it's even.
e. If num is even, add it to even_sum.
f. Return the even_sum.

Code:

Output:

Result: Therefore, the above python code has been demonstrated successfully

7 . Aim: Take a list of 10 elements. Split it into middle and store the elements in two
different lists.
E.g.- INITIAL list:
58 24 13 15 63 9 8 81 1 78
After splitting:
58 24 13 15 63
9 8 81 1 78

Algorithm:
a. Define a function named split_list that takes an input_list as an argument.
b. Calculate the middle index by using integer division (//) of the length of the list by 2.
This will give the index where the list will be split.
c. Use list slicing to create two new lists: first_half will contain the elements from the
start of the input_list up to the middle, and second_half will contain the elements
from the middle to the end.

Code:

Output:

Result: Therefore, the above python code has been demonstrated successfully
8 .Aim: Write a function to find factorial of a number and stores the factorials calculated in
a dictionary
Algorithm:
a. Define a function named factorial that calculates the factorial of a given number n.
It's a recursive function that stops when n is 0 or 1, as 0! and 1! are defined as 1.
b. Define a function named calculate_and_store_factorials that takes a number n as an
argument.
c. Initialize an empty dictionary factorials.
d. Use a loop to iterate from 0 to n.
e. For each iteration, calculate the factorial of the current number and store it in the
factorials dictionary with the number as the key.
f. Return the factorials dictionary.
g. In the main program, set n to the desired value to calculate factorials up to that
number.
h. Call calculate_and_store_factorials(n) to get the dictionary of factorials.
i. Print the factorials.:

Code:

Output:
Result: Therefore, the above python code has been demonstrated successfully

9 .Aim: Count the number of occurrences of each letter in word "MISSISSIPPI". Store
count of every letter with the letter in a dictionary. Write a python function
Algorithm:
a. Define a function named count_occurrences that takes a string word as an argument.
b. Initialize an empty dictionary letter_counts.
c. Iterate through each letter in the word.
d. Check if the letter is already a key in letter_counts.
e. If it is, increment the corresponding count.
f. If it's not, create a new entry with the letter as the key and set the count to 1.
g. Return the letter_counts dictionary.
h. In the main program, set word to "MISSISSIPPI" as specified.
i. Call count_occurrences(word) to get the dictionary of letter counts.

Code:

Output:

Result: Therefore, the above python code has been demonstrated successfully
10 .Aim: Ask user to give integer inputs to make a tuple. Store only even values given and
print the values in a list.
Algorithm:
a. Define a function named get_even_values that does the following:
b. Initialize an empty list even_values to store even integers.
c. Start an infinite loop.
d. Prompt the user to enter an integer or type 'done' to finish.
e. If the user enters 'done', exit the loop.
f. Try to convert the user input to an integer.
g. If successful, check if it's even (using num % 2 == 0).
h. If it's even, append it to the even_values list.
i. If there's a ValueError, print an error message.
j. Return the even_values list.
k. In the main program:
l. Call get_even_values() to get the list of even values entered by the user.
m. Print the list of even values.

Code:

Output:
Result: Therefore, the above python code has been demonstrated successfully

11. Aim: Write a program to calculate the exp(x,y) using recursive functions
Algorithm:
a. Define a function exp_recursive that takes two arguments, x (base) and y
(exponent).
b. If y is 0, return 1 because any number raised to the power of 0 is 1.
c. If y is positive, recursively call exp_recursive with y - 1 and multiply the result by x.
d. If y is negative, calculate the reciprocal by taking the reciprocal of the result of
exp_recursive(x, -y).
e. In the main program, set x and y to the desired values.
f. Call exp_recursive(x, y) to calculate the result of x^y.

Code:

Output:

Result: Therefore, the above python code has been demonstrated successfully

12. Aim: Write a program to implement the Tower of Hanoi problem using recursive
function
Algorithm:
a. Define a function tower_of_hanoi that takes four arguments: n (number of disks),
source (source peg), auxiliary (auxiliary peg), and target (target peg).
b. If n is greater than 0, do the following:
c. Move n - 1 disks from source to auxiliary, using target as the auxiliary peg.
d. Move the nth disk from source to target.
e. Move n - 1 disks from auxiliary to target, using source as the auxiliary peg.
f. In the main program, set the number of disks (num_disks) and the labels for the
source, auxiliary, and target pegs.
g. Call tower_of_hanoi with the specified parameters to solve the Tower of Hanoi
problem.

Code:

Output:

Result: Therefore, the above python code has been demonstrated successfully
Date: 27/09/23 (week 10)
TITLE: Classes, Objects and Methods
1 .Aim: Write a program that has class Cars. Create two objects and set Car1 to be a red
convertible with price 10 lakhs and name Pugo. Car2 to be a blue sedan named Mavo worth
6 lakhs

Algorithm:
a. Define a class named Car with an __init__ method that initializes attributes such as
name, color, type, and price.
b. Define a method display_info within the Car class to display the information of the
car.
c. Create an instance of the Car class named Car1 with the specified attributes
(name="Pugo", color="red", type="convertible", price=10).
d. Create another instance of the Car class named Car2 with the specified attributes
(name="Mavo", color="blue", type="sedan", price=6).
e. Print the information of Car1 and Car2.

Code:

Output:
Result: Therefore, the above python code has been demonstrated successfully.

2 .Aim: Write a program to compare length of 2 strings using __cmp__ function.


Algorithm:
a. Define a class StringComparator that takes a string as input in its constructor.
b. Define the __cmp__ method within the class.
c. In the __cmp__ method, compare the lengths of self.string and other.string.
d. If self.string is shorter, return -1.
e. If the lengths are equal, return 0.
f. Otherwise, return 1.
g. In the main program, create two instances of StringComparator with different
strings.
h. Based on the comparison result, print an appropriate message

Code:

Output:

Result: Therefore, the above python code has been demonstrated successfully
3 .Aim: Make a class triangle. Enter its three sides and calculate its area
Algorithm:
a. Define a class named Triangle with an __init__ method that initializes the three sides
of the triangle.
b. Define a method named calculate_area within the Triangle class to calculate the
area.
c. Use Heron's formula: area = sqrt(s * (s - a) * (s - b) * (s - c)), where s is the semi-
perimeter and a, b, and c are the sides of the triangle.
d. In the main program, prompt the user to enter the lengths of the three sides.
e. Create an instance of the Triangle class with the provided side lengths.
f. Call the calculate_area method to calculate the area.
g. Print the calculated area.

Code:

Output:

Result: Therefore, the above python code has been demonstrated successfully
4 .Aim: Write a program that uses a class attribute to define some default titles for faculty
in a college. Display the name along with title and department of the college

Algorithm:
a. Define a class named Faculty.
b. Add a class attribute named default_title with a default value like "Lecturer". This
attribute will hold the default title for all faculty members.
c. Define an __init__ method that takes name and department as arguments. Inside the
__init__ method, set name, title (using the class attribute default_title), and
department.
d. Define a method named display_info to print the faculty member's information.
e. In the main program, create two instances of the Faculty class (faculty1 and
faculty2) with different names and departments.
f. Call the display_info method for each instance to display the information.

Code:

Output:

Result: Therefore, the above python code has been demonstrated successfully
5 .Aim: Write a program that has a class point with attributes as the X and Y co-ordinates.
Make two objects of this class and find the midpoint of both the points

Algorithm:
a. Define a class named Point with an __init__ method that initializes the x and y
attributes.
b. Define a method named calculate_midpoint that takes another point (other_point)
as an argument. Calculate the midpoint coordinates (mid_x and mid_y) by averaging
the x and y coordinates of both points. Create a new Point object with these
coordinates and return it.
c. Define a method named display_point to print the x and y coordinates of a point.
d. In the main program, create two instances of the Point class (point1 and point2)
with different coordinates.
e. Print the coordinates of both points.
f. Calculate the midpoint between point1 and point2 using the calculate_midpoint
method.
g. Print the coordinates of the midpoint.

Code:
Output:

Result: Therefore, the above python code has been demonstrated successfully
6 .Aim: Write a program to deposit or withdraw money in a bank account

Algorithm:
a. Define a class named BankAccount with an __init__ method that initializes the
balance attribute.
b. Define a method named deposit that takes an amount as an argument and adds it to
the balance.
c. Define a method named withdraw that takes an amount as an argument and
subtracts it from the balance, but checks if there are sufficient funds before doing so.
d. In the main program, create an instance of the BankAccount class with an initial
balance (in this case, 1000 units).
e. Deposit 500 units into the account and print the updated balance.
f. Withdraw 200 units from the account and print the updated balance.
g. Attempt to withdraw 1500 units, which will result in an insufficient funds message.

Code:

Output:

Result: Therefore, the above python code has been demonstrated successfully
Date: 27/09/23 (week 11)
TITLE: . Inheritance
1 Aim: Write a program for a publishing company that markets books and CDs. Write
a class Publication that stores title and price. Derive a class Book which has an
additional member as number of pages. Derive another class Lecture from
Publication with additional member play time. Create objects and display outputs
accordingly

Algorithm:
a. Define a class named Publication with an __init__ method that initializes title and
price attributes. It also has a method display_info to print the title and price.
b. Define a class named Book that inherits from Publication. It has an additional
attribute num_pages and overrides the display_info method to include the number
of pages.
c. Define a class named Lecture that inherits from Publication. It has an additional
attribute play_time (in minutes) and overrides the display_info method to include
the play time.
d. In the main program, create instances of Book and Lecture classes with different
titles, prices, and additional attributes.
e. Call the display_info method to display the information for each object.

Code:
Output:
Result: Therefore, the above python code has been demonstrated successfully

2 .Aim: MULTIPLE. Define a class student with data members as ID number and name.
Define a class Grade that has data member CGPA. Derive a class scholarship which is
derived from both these classes to compute scholarship as follows: Rs.10,000/- pm if
CGPA>9. Rs.7500/-pm if CGPA>8. Rs.5000/- pm if CGPA>7.5. Create an object of
scholarship and display

Algorithm:
a. Define a class named Student with data members ID and name.
b. Define a class named Grade with data member CGPA.
c. Define a class named Scholarship that is derived from both Student and Grade.
d. Add a method compute_scholarship within the Scholarship class that computes the
scholarship amount based on the CGPA.
e. Add a method display_info within the Scholarship class to display the student's
information along with the computed scholarship amount.
f. In the main program, create instances of Scholarship class with different student
IDs, names, and CGPAs.
g. Call the display_info method for each student to display their information and
scholarship

Code:
Output:

Result: Therefore, the above python code has been demonstrated successfully
3.Aim: “Inheritance”. Define a class which has two objects of another class. Create a class
Point with members as x, y coordinates. Create another class Location that has objects
source and destination of class Point. Compute the distance between these locations and
print the distance

Algorithm:
a. Define a class named Point with attributes x and y to represent coordinates.
b. Define another class named Location with attributes source and destination, which
are objects of class Point.
c. Add a method compute_distance within the Location class to calculate the distance
between the source and destination points using the distance formula.
d. Add a method display_distance within the Location class to print the computed
distance.
e. In the main program, create instances of Point for the source and destination
coordinates.
f. Create an instance of Location with the source and destination points.
g. Call display_distance to calculate and print the distance between the locations.

Code:

Output:

Result: Therefore, the above python code has been demonstrated successfully
4 .Aim: MULTI-PATH. Create a base class Family with member surname. Create a derived
class 1 Father with father name and occupation. Create another derived class 2 Mother
with mother name and age. Create a Derived class 3 child from Father and Mother with
additional member of child name. Create an object of child and print the details of the
family members
Algorithm:
a. Define a class named Family with a member surname to represent the family's
surname.
b. Define a class named Father derived from Family with members father_name and
occupation to represent the father's name and occupation.
c. Define a class named Mother derived from Family with members mother_name and
age to represent the mother's name and age.
d. Define a class named Child derived from both Father and Mother with an additional
member child_name to represent the child's name.
e. In the Child class, initialize the parent classes Father and Mother with the
appropriate arguments using Father.__init__ and Mother.__init__.
f. Define a method display_info within the Child class to print the details of the family
members.
g. In the main program, create an instance of Child with the necessary details.
h. Call display_info to print the details of the family members.

code:

Output:
Result: Therefore, the above python code has been demonstrated successfully
4 .Aim: Write a program that has an Abstract class Polygon. Derive Three classes
Rectangle, Square and Triangle from Polygon. Write methods to get the details of
their dimensions and then calculate the surface area.

Algorithm:
a. Define an abstract class Polygon with two abstract methods get_dimensions and
calculate_surface_area.
b. Derive three classes Rectangle, Square, and Triangle from Polygon.
c. Implement the get_dimensions method in each derived class to get the necessary
dimensions (length, width, side, base, height).
d. Implement the calculate_surface_area method in each derived class to compute the
surface area based on their respective formulas.
e. In the main program, create instances of Rectangle, Square, and Triangle.
f. Call get_dimensions and calculate_surface_area methods for each instance to get the
details and calculate the surface area.

Code:
Output:

Result: Therefore, the above python code has been demonstrated successfully
Date: 25/10/23 (week 12)
TITLE: Python Data structures
1 .Aim: To implement Queue data structure in python
Algorithm:
a. Create a class Queue:
 Initialize an empty list, items, to serve as the internal data structure.
b. Define the is_empty method:
 Check if the items list is empty:
 If it is, return True.
 If it is not, return False.
c. Define the enqueue method:
 Accept an item as a parameter.
 Append the item to the end of the items list using the append method.
d. Define the dequeue method:
e. Check if the queue is not empty:
 Remove and return the item at index 0 (the front of the queue) using pop(0) and
return it.
 If the queue is empty, return None.
f. Define the peek method:
 Check if the queue is not empty:
 Return the item at index 0 (the front of the queue) without removing it.
 If the queue is empty, return None.
g. Define the size method:
 Return the number of items in the items list using the len function.
h. Example usage:
 Create an instance of the Queue class.
 Use enqueue to add items to the queue.
 Use peek to access the front item.
 Use dequeue to remove and retrieve items from the queue.
 Use is_empty to check if the queue is empty.
 Use size to determine the number of items in the queue.

Code:
Output:

Result: Therefore, the python code has been demonstrated successfully


2 .Aim: To implement Stack data structure in python
Algorithm:
a. Create a class Stack:
 Initialize an empty list, items, to serve as the internal data structure.
b. Define the is_empty method:
 Check if the items list is empty:
 If it is, return True.
 If it's not, return False.
c. Define the push method:
 Accept an item as a parameter.
 Append the item to the end of the items list using the append method.
d. Define the pop method:
 Check if the stack is not empty:
 Remove and return the item at the end of the items list using pop.
 If the stack is empty, return None.
e. Define the peek method:
 Check if the stack is not empty:
 Return the item at the end of the items list without removing it.
 If the stack is empty, return None.
f. Define the size method:
 Return the number of items in the items list using the len function.
g. Example usage:
 Create an instance of the Stack class.
 Use push to add items to the stack.
 Use peek to access the top item.
 Use pop to remove and retrieve items from the stack.
 Use is_empty to check if the stack is empty.
 Use size to determine the number of items in the stack.
Code:
Output:

Result: Therefore, the python code has been demonstrated successfully

3 .Aim: To implement Linked list data structure in python


Algorithm:
a. Create a class Node:
 Initialize a node with a data value and a next reference initially set to None.
b. Create a class LinkedList:
 Initialize an empty linked list with head initially set to None.
c. Define the is_empty method:
 Check if the head of the linked list is None.
 If it is, return True to indicate that the list is empty.
 If it's not, return False.
d. Define the append method:
 Accept a data value as a parameter.
 Create a new node with the given data.
 If the list is empty (i.e., head is None), set head to the new node.
 Otherwise, traverse the list to find the last node (the one with next equal to None)
and make it point to the new node.
e. Define the display method:
 Initialize a current variable to the head of the linked list.
 While current is not None, print the data of the current node followed by " -> ".
 Print "None" to indicate the end of the list.

Code:
Output:

Result: Therefore, the python code has been demonstrated successfully


4 . Aim: To implement Hash Table data structure in python
Algorithm:
a. Create a class HashTable:
 Initialize the hash table with a given size.
 create a list called table with sublists for storing key-value pairs.
b. Define the _hash method:
 Accept a key as a parameter.
 Calculate the hash code for the key using the built-in hash function and take the
modulo of the size to get an index within the range of the table.
c. Define the set method:
 Accept a key and a value as parameters.
 Calculate the index for the key using the _hash method.
 Iterate through the list at the calculated index:
 If the key is found, update the associated value.
 If the key is not found, append a new key-value pair to the list.
d. Define the get method:
 Accept a key as a parameter.
 Calculate the index for the key using the _hash method.
 Iterate through the list at the calculated index:
 If the key is found, return the associated value.
 If the key is not found, raise a KeyError.
e. Define the remove method:
 Accept a key as a parameter.
 Calculate the index for the key using the _hash method.
 Iterate through the list at the calculated index:
 If the key is found, remove the key-value pair from the list.
 If the key is not found, raise a KeyError.
f. Example usage:
 Create an instance of the HashTable class with a specified size.
 Use the set method to add key-value pairs.
 Use the get method to retrieve values by key.
 Use the remove method to delete key-value pairs.
 Handle potential exceptions like KeyError when attempting to access or remove
nonexistent keys.

Code:
Output:

Result: Therefore, the python code has been demonstrated successfully

You might also like