UNIT-IV
Files and OOPS
Experiment 18: Write a program to sort words in a file and put them in another file. The output file should have only lower-case
words, so any upper-case words from source must be lowered.
Aim:
To write a Python program that reads words from a file, converts them to lowercase, sorts them alphabetically, and
writes the sorted words into another file.
Algorithm:
1. Start.
2. Open the input file in read mode.
3. Read the contents of the file into a variable.
4. Convert all characters in the text to lowercase using the lower() function.
5. Split the text into individual words using the split() function.
6. Sort the list of words alphabetically using the sorted() function.
7. Open a new output file in write mode.
8. Write each sorted word (one per line) into the output file.
9. Close both files.
10. End.
Program:
input_file = "[Link]"
output_file = "[Link]"
with open(input_file, "r") as f:
text = [Link]()
words = [Link]().split()
sorted_words = sorted(words)
with open(output_file, "w") as f:
for word in sorted_words:
[Link](word + "\n")
print("Words have been sorted and written to", output_file)
Input:
input_file.txt
Python is Great and Simple
Output
and
great
is
python
simple
Result:
The program successfully reads words from a file, converts them to lowercase, sorts them alphabetically, and writes them
into another file.
Experiment 19: Python program to print each line of a file in reverse order
Aim: To write a Python program that reads each line of a file and prints it in reverse order.
Algorithm:
1. Start.
2. Open the input file in read mode.
3. Read all lines from the file using the readlines() function.
4. For each line in the list:
Remove the newline character using strip().
Reverse the line using slicing [::-1].
Print the reversed line.
5. Close the file.
6. End.
Program:
# Step 1: Specify the input file name
input_file = "[Link]"
# Step 2: Open the file in read mode
with open(input_file, "r") as f:
lines = [Link]()
# Step 3: Print each line in reverse order
for line in lines:
reversed_line = [Link]()[::-1]
print(reversed_line)
INPUT:
[Link]
Python is fun
Learning is easy
Output:
nuf si nohtyP
ysaE si gninraeL
Result:
The program successfully reads each line from a file and prints the reversed content of each line.
Experiment 20: Python program to compute the number of characters, words and lines in a file.
Aim:
To write a Python program that computes the number of characters, words, and lines in a given file.
Algorithm:
1. Start.
2. Open the input file in read mode.
3. Initialize counters for characters, words, and lines to zero.
4. Read all lines from the file using the readlines() function.
5. For each line in the file:
Increment the line counter by 1.
Increment the word counter by the number of words in the line (using split()).
Increment the character counter by the number of characters in the line (using len()).
6. Print the total number of lines, words, and characters.
7. Close the file.
8. End.
Program:
# Step 1: Specify the input file name
input_file = "[Link]"
# Step 2: Initialize counters
num_lines = 0
num_words = 0
num_chars = 0
# Step 3: Open the file and process its content
with open(input_file, "r") as f:
for line in f:
num_lines += 1
num_words += len([Link]())
num_chars += len(line)
# Step 4: Display the results
print("Number of lines:", num_lines)
print("Number of words:", num_words)
print("Number of characters:", num_chars)
Input:
[Link]
Python is easy to learn
It is a powerful language
Output:
Number of lines: 2
Number of words: 9
Number of characters: 53
Result:
The program successfully computes and displays the number of lines, words, and characters in a given file.
Experiment 21: Write a program to create, display, append, insert and reverse the order of the items in the array.
Aim: To write a Python program to create, display, append, insert, and reverse the order of items in an array.
Algorithm:
1. Start.
2. Import the array module.
3. Create an array using the array() function with a predefined list of elements.
4. Display the original array elements.
5. Append a new element to the array using the append() function.
6. Insert an element at a specific position using the insert() function.
7. Reverse the order of elements using the reverse() function.
8. Display the array after each operation.
9. End.
Program:
# Step 1: Import the array module
from array import *
# Step 2: Create an array of integers
arr = array('i', [10, 20, 30, 40, 50])
# Step 3: Display the original array
print("Original array:", [Link]())
# Step 4: Append an element to the array
[Link](60)
print("After appending 60:", [Link]())
# Step 5: Insert an element at index 2
[Link](2, 25)
print("After inserting 25 at index 2:", [Link]())
# Step 6: Reverse the array
[Link]()
print("Array in reverse order:", [Link]())
Output:
Original array: [10, 20, 30, 40, 50]
After appending 60: [10, 20, 30, 40, 50, 60]
After inserting 25 at index 2: [10, 20, 25, 30, 40, 50, 60]
Array in reverse order: [60, 50, 40, 30, 25, 20, 10]
Result:
The program successfully creates, displays, appends, inserts, and reverses the elements of an array using Python.
Experiment 22: Write a program to add, transpose and multiply two matrices.
Aim:
To write a Python program to add, transpose, and multiply two matrices.
Algorithm:
1. Start.
2. Create two matrices (2D lists) of the same size.
3. Matrix Addition:
4. Use nested loops to add corresponding elements of both matrices.
5. Matrix Transpose:
6. Swap rows and columns using nested loops or list comprehension.
7. Matrix Multiplication:
8. Multiply the two matrices using the formula:C [i][ j]=∑ A [i][k ]× B [k ][ j]
9. Display the results of addition, transpose, and multiplication.
10. End.
Program:
# Step 1: Define two matrices
A = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
B = [[9, 8, 7],
[6, 5, 4],
[3, 2, 1]]
# Step 2: Matrix Addition
add_result = [[A[i][j] + B[i][j] for j in range(len(A[0]))] for i in range(len(A))]
# Step 3: Transpose of Matrix A
transpose_A = [[A[j][i] for j in range(len(A))] for i in range(len(A[0]))]
# Step 4: Matrix Multiplication
multiply_result = [[sum(A[i][k] * B[k][j] for k in range(len(A[0])))
for j in range(len(B[0]))] for i in range(len(A))]
# Step 5: Display the results
print("Matrix A:")
for row in A:
print(row)
print("\nMatrix B:")
for row in B:
print(row)
print("\nAddition of A and B:")
for row in add_result:
print(row)
print("\nTranspose of Matrix A:")
for row in transpose_A:
print(row)
print("\nMultiplication of A and B:")
for row in multiply_result:
print(row)
Output:
Matrix A:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
Matrix B:
[9, 8, 7]
[6, 5, 4]
[3, 2, 1]
Addition of A and B:
[10, 10, 10]
[10, 10, 10]
[10, 10, 10]
Transpose of Matrix A:
[1, 4, 7]
[2, 5, 8]
[3, 6, 9]
Multiplication of A and B:
[30, 24, 18]
[84, 69, 54]
[138, 114, 90]
Result:
The program successfully performs addition, transpose, and multiplication of two matrices in Python.
Experiment 23: Write a Python program to create a class that represents a shape. Include methods to calculate its area and
perimeter. Implement subclasses for different shapes like circle, triangle, and square
Aim:
To write a Python program to create a class that represents a shape, including methods to calculate its area and
perimeter. Implement subclasses for different shapes like Circle, Triangle, and Square.
Algorithm:
1. Start.
2. Create a base class Shape that contains two methods:
3. area() → to compute the area.
4. perimeter() → to compute the perimeter.
5. Create a subclass Circle that inherits from Shape and implements:
6. Area = π × r²
7. Perimeter = 2 × π × r
8. Create a subclass Square that inherits from Shape and implements:
9. Area = side × side
10. Perimeter = 4 × side
11. Create a subclass Triangle that inherits from Shape and implements:
12. Perimeter = a + b + c
13. Area = √[s(s - a)(s - b)(s - c)], where s = (a + b + c) / 2
14. Create objects for each shape and display their area and perimeter.
15. End.
Program:
import math
# Step 1: Create base class Shape
class Shape:
def area(self):
pass
def perimeter(self):
pass
# Step 2: Create subclass Circle
class Circle(Shape):
def __init__(self, radius):
[Link] = radius
def area(self):
return [Link] * [Link] ** 2
def perimeter(self):
return 2 * [Link] * [Link]
# Step 3: Create subclass Square
class Square(Shape):
def __init__(self, side):
[Link] = side
def area(self):
return [Link] ** 2
def perimeter(self):
return 4 * [Link]
# Step 4: Create subclass Triangle
class Triangle(Shape):
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def perimeter(self):
return self.a + self.b + self.c
def area(self):
s = (self.a + self.b + self.c) / 2
return [Link](s * (s - self.a) * (s - self.b) * (s - self.c))
# Step 5: Create objects and display results
circle = Circle(5)
square = Square(4)
triangle = Triangle(3, 4, 5)
print("Circle: Area =", round([Link](), 2), ", Perimeter =", round([Link](), 2))
print("Square: Area =", [Link](), ", Perimeter =", [Link]())
print("Triangle: Area =", round([Link](), 2), ", Perimeter =", [Link]())
Output
Circle: Area = 78.54 , Perimeter = 31.42
Square: Area = 16 , Perimeter = 16
Triangle: Area = 6.0 , Perimeter = 12
Result:
The program successfully creates a base class for shapes and implements subclasses for Circle, Triangle, and Square to
calculate their area and perimeter.