WEEK4
WEEK4
1.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.
f=open("1.txt","rt")
data=myfile.read()
print(data)
d=f.read().split()
print(d)
print(a)
OUTPUT:
2.Python program to print each line of a file in reverse order.
#with open('1.txt', 'r') as file:
file=open('1.txt','r')
print(line.rstrip()[::-1])
OUTPUT:
3.Python program to compute the number of characters, words and lines in a file.
def count(file_path):
# Initialize counters
num_lines = 0
num_words = 0
num_chars = 0
# Open the file in read mode
with open("1.txt", 'r') as file:
# Read each line from the file
for line in file:
# Increment line counter
num_lines += 1
# Increment character counter (including whitespaces)
num_chars += len(line)
# Split the line into words and count them
num_words += len(line.split())
# Return the counts
return num_lines, num_words, num_chars
# Specify the file path
file_path = '1.txt'
# Call the function and get the counts
lines, words, characters = count(file_path)
# Print the results
print(f"Lines: {lines}")
print(f"Words: {words}")
print(f"Characters: {characters}")
OUTPUT:
4.Write a program to create, display, append, insert and reverse the order of the
items in the array.
import array
# Function to display the array
def display_array(arr):
print("Array:", arr.tolist()) # Convert to list for easier display
# 1. Create an array of integers
arr = array.array('i')
n = int(input("Enter the number of elements: "))
print("Enter the elements:")
for i in range(n):
#print(i)
arr.append(int(input()))
print("Created array:")
display_array(arr)
# 2. Append an item to the array
arr.append(6)
print("\nAfter appending 6:")
display_array(arr)
# 3. Insert an item at a specific position
arr.insert(2, 99) # Insert 99 at index 2
print("\nAfter inserting 99 at index 2:")
display_array(arr)
# 4. Reverse the array
arr.reverse()
print("\nAfter reversing the array:")
display_array(arr)
OUTPUT:
5.Write a program to add, transpose and multiply two matrices.
row = []
result.append(row)
return result
def transpose_matrix(mat):
result = []
row = []
result.append(row)
return result
result = []
row = []
product = 0
result.append(row)
return result
# Input matrices
mat1 = []
for i in range(rows):
for j in range(cols):
mat1.append(row)
mat2 = []
for i in range(rows):
for j in range(cols):
mat2.append(row)
print("Matrix Addition:")
result_transpose = transpose_matrix(mat1)
print(row)
print("\nMatrix Multiplication:")
print(row)
OUTPUT:
6.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.
import math
class Shape:
def area(self):
"""Method to calculate the area of the shape. Should be overridden by
subclasses."""
raise NotImplementedError("Subclasses should implement this method."
def perimeter(self):
"""Method to calculate the perimeter of the shape. Should be overridden by
subclasses."""
raise NotImplementedError("Subclasses should implement this method.")
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return math.pi * (self.radius ** 2)
def perimeter(self):
return 2 * math.pi * self.radius
class Triangle(Shape):
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def area(self):
# Using Heron's formula
s = (self.a + self.b + self.c) / 2
return math.sqrt(s * (s - self.a) * (s - self.b) * (s - self.c))
def perimeter(self):
return self.a + self.b + self.c
class Square(Shape):
def __init__(self, side_length):
self.side_length = side_length
def area(self):
return self.side_length ** 2
def perimeter(self):
return 4 * self.side_length
# Create instances of each shape
circle = Circle(5)
triangle = Triangle(3, 4, 5)
square = Square(4)
# Print area and perimeter of each shape
print(f"Circle: Area = {circle.area()}, Perimeter = {circle.perimeter()}")
print(f"Triangle: Area = {triangle.area()}, Perimeter = {triangle.perimeter()}")
print(f"Square: Area = {square.area()}, Perimeter = {square.perimeter()}")
OUTPUT: