0% found this document useful (0 votes)
6 views9 pages

Python Unit 4 Programs

The document contains multiple Python programming tasks including sorting words in a file, reversing lines, counting characters, words, and lines in a file, manipulating arrays, performing matrix operations, and creating a shape class with subclasses for different shapes. Each task includes a clear aim, sample code, and output results demonstrating successful execution. Overall, it serves as a guide for implementing basic file handling, data manipulation, and object-oriented programming in Python.

Uploaded by

tejasree allam
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)
6 views9 pages

Python Unit 4 Programs

The document contains multiple Python programming tasks including sorting words in a file, reversing lines, counting characters, words, and lines in a file, manipulating arrays, performing matrix operations, and creating a shape class with subclasses for different shapes. Each task includes a clear aim, sample code, and output results demonstrating successful execution. Overall, it serves as a guide for implementing basic file handling, data manipulation, and object-oriented programming in Python.

Uploaded by

tejasree allam
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

Unit-4

[Link] 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 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.
Program:
# Create a sample input file

with open("[Link]", "w") as f:

[Link]("Apple banana Mango grape ORANGE")

print("[Link] created successfully!")

o/p:[Link] created successfully!

# Function to sort words from input file and write to output file

def sort_words(input_file, output_file):

try:

# Read words from input file

with open(input_file, "r") as file:

words = [Link]().split()

# Convert words to lowercase

lower_words = [[Link]() for word in words]

# Sort words alphabetically

sorted_words = sorted(lower_words)
# Write sorted words to output file

with open(output_file, "w") as file:

for word in sorted_words:

[Link](word + "\n")

print("Words sorted and written successfully!")

except FileNotFoundError:

print("Error: Input file not found.")

# Run the function

sort_words("[Link]", "[Link]")

o/p:

Words sorted and written successfully!

# Display contents of output file

with open("[Link]", "r") as f:

print([Link]())
Output:
apple
banana
grape
mango
orange

Result:

Hence above code is executed successfully.


19. Python program to print each line of a file in reverse order.
Aim:
To Write a Python program to print each line of a file in reverse order.
Program:
# Create sample file
with open("[Link]", "w") as f:
[Link]("Hello World\nPython Programming\nGoogle Colab")
print("Sample file created.")
o/p: Sample file created.
# Function to print each line in reverse order
def reverse_lines(filename):
try:
with open(filename, 'r') as file:
for line in file:
# Remove newline and reverse the line
reversed_line = [Link]()[::-1]
print(reversed_line)
except FileNotFoundError:
print("Error: File not found.")
# Call function
reverse_lines("[Link]")
o/p: dlroW olleH
gnimmargorP nohtyP
baloC elgooG
Result:
Hence above code is executed successfully.

20. Python program to compute the number of characters, words and lines in a
file.
Aim:
To write a Python program to compute the number of characters, words and lines
in a file.
Program:
with open("[Link]", "w") as f:
[Link]("Hello World\nPython is Easy")

print("Sample file created.")


# Function to count characters, words, and lines
def count_file_details(filename):
try:
with open(filename, 'r') as file:
content = [Link]()
# Count characters (including spaces)
characters = len(content)
# Count words
words = len([Link]())
# Count lines
lines = [Link]('\n') + 1 if content else 0
print("Number of characters:", characters)
print("Number of words:", words)
print("Number of lines:", lines)
except FileNotFoundError:
print("Error: File not found.")
# Call function
count_file_details("[Link]")

Output:
Sample file created.
Number of characters: 26
Number of words: 5
Number of lines: 2
Result:
Hence above code is executed successfully.

21. Write a program to create, display, append, insert and reverse the order of
the items in the array.
Aim:
To Write a program to create, display, append, insert and reverse the order of the
items in the array.
Program:
# Create an array (using list in Python)
arr = []
# Take number of elements from user
n = int(input("Enter number of elements: "))
print("Enter elements:")
# Add elements to array
for i in range(n):
element = input()
[Link](element)
# Display array
print("Array elements are:", arr)
# Append an item
append_item = input("Enter item to append: ")
[Link](append_item)
print("After append:", arr)
# Insert an item
insert_item = input("Enter item to insert: ")
position = int(input("Enter position (index) to insert: "))
[Link](position, insert_item)
print("After insertion:", arr)
# Reverse the array
[Link]()
print("After reversing:", arr)
Output:
Enter number of elements: 3
Enter elements:
10
20
30
Array elements are: ['10', '20', '30']
Enter item to append: 40
After append: ['10', '20', '30', '40']
Enter item to insert: 15
Enter position (index) to insert: 1
After insertion: ['10', '15', '20', '30', '40']
After reversing: ['40', '30', '20', '15', '10']
Result:
Hence above code is executed successfully.
[Link] a program to add, transpose and multiply two matrices.
Aim:
To Write a program to add, transpose and multiply two matrices.
Program:
# Input matrix size
rows = int(input("Enter number of rows: "))
cols = int(input("Enter number of columns: "))
print("\nEnter elements of Matrix A:")
A = []
for i in range(rows):
row = []
for j in range(cols):
[Link](int(input()))
[Link](row)
print("\nEnter elements of Matrix B:")
B = []
for i in range(rows):
row = []
for j in range(cols):
[Link](int(input()))
[Link](row)
# Matrix Addition
print("\nMatrix Addition (A + B):")
result_add = []
for i in range(rows):
row = []
for j in range(cols):
[Link](A[i][j] + B[i][j])
result_add.append(row)
for row in result_add:
print(row)
# Transpose of Matrix A
print("\nTranspose of Matrix A:")
transpose = []
for j in range(cols):
row = []
for i in range(rows):
[Link](A[i][j])
[Link](row)
for row in transpose:
print(row)
# Matrix Multiplication (A × B)
print("\nMatrix Multiplication (A × B):")
result_mul = []
for i in range(rows):
row = []
for j in range(cols):
sum_value = 0
for k in range(cols):
sum_value += A[i][k] * B[k][j]
[Link](sum_value)
result_mul.append(row)
for row in result_mul:
print(row)
Output:
Enter number of rows: 2
Enter number of columns: 2
Enter elements of Matrix A:
6
8
10
12
Enter elements of Matrix B:
1
3
2
4
Matrix Addition (A + B):
[7, 11]
[12, 16]
Transpose of Matrix A:
[6, 10]
[8, 12]
Matrix Multiplication (A × B):
[22, 50]
[34, 78]
Result:Hence above code is executed successfully.
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. Include
methods to calculate its area and perimeter. Implement subclasses for different
shapes like circle, triangle, and square.
Program:
import math
# Base Class
class Shape:
def area(self):
pass
def perimeter(self):
pass
# 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]
# Subclass: Square
class Square(Shape):
def __init__(self, side):
[Link] = side
def area(self):
return [Link] ** 2
def perimeter(self):
return 4 * [Link]
# Subclass: Triangle
class Triangle(Shape):
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def area(self):
# Heron's formula
s = (self.a + self.b + self.c) / 2
return [Link](s * (s - self.a) * (s - self.b) * (s - self.c))
def perimeter(self):
return self.a + self.b + self.c

# Example Usage
# Circle
circle = Circle(5)
print("Circle Area:", [Link]())
print("Circle Perimeter:", [Link]())
# Square
square = Square(4)
print("\nSquare Area:", [Link]())
print("Square Perimeter:", [Link]())
# Triangle
triangle = Triangle(3, 4, 5)
print("\nTriangle Area:", [Link]())
print("Triangle Perimeter:", [Link]())
Output:
Circle Area: 78.53981633974483
Circle Perimeter: 31.41592653589793
Square Area: 16
Square Perimeter: 16
Triangle Area: 6.0
Triangle Perimeter: 12
Result:Hence above code is executed successfully

You might also like