[go: up one dir, main page]

0% found this document useful (0 votes)
10 views12 pages

WEEK4

The document contains multiple Python programming tasks including sorting words from a file, printing lines in reverse order, counting characters, words, and lines in a file, manipulating arrays, performing matrix operations, and creating a shape class with subclasses for different geometric shapes. Each task includes code snippets and expected outputs. The tasks are designed to demonstrate various programming concepts and techniques in Python.

Uploaded by

tmeenakshi
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)
10 views12 pages

WEEK4

The document contains multiple Python programming tasks including sorting words from a file, printing lines in reverse order, counting characters, words, and lines in a file, manipulating arrays, performing matrix operations, and creating a shape class with subclasses for different geometric shapes. Each task includes code snippets and expected outputs. The tasks are designed to demonstrate various programming concepts and techniques in Python.

Uploaded by

tmeenakshi
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/ 12

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")

with open("1.txt") as myfile:

data=myfile.read()

print(data)

d=f.read().split()

print(d)

a=[item.lower() for item in 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')

for line in file:

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.

def add_matrices(mat1, mat2):


result = []

for i in range(len(mat1)): # Iterate through rows

row = []

for j in range(len(mat1[0])): # Iterate through columns

row.append(mat1[i][j] + mat2[i][j]) # Add corresponding elements

result.append(row)

return result

# Function to transpose a matrix

def transpose_matrix(mat):

result = []

for i in range(len(mat[0])): # Iterate through columns (because rows become


columns)

row = []

for j in range(len(mat)): # Iterate through rows

row.append(mat[j][i]) # Transpose element

result.append(row)

return result

# Function to multiply two matrices

def multiply_matrices(mat1, mat2):

result = []

for i in range(len(mat1)): # Iterate through rows of mat1

row = []

for j in range(len(mat2[0])): # Iterate through columns of mat2

product = 0

for k in range(len(mat1[0])): # Multiply and sum elements

product += mat1[i][k] * mat2[k][j]


row.append(product)

result.append(row)

return result

# Input matrices

rows = int(input("Enter the number of rows: "))

cols = int(input("Enter the number of columns: "))

mat1 = []

print("elements for first matrix")

for i in range(rows):

row = [] # Create an empty list for the current row

for j in range(cols):

element = int(input(f"Enter element at position [{i+1},{j+1}]: "))

row.append(element) # Append element to the current row

mat1.append(row)

mat2 = []

print("elements for second matrix")

for i in range(rows):

row = [] # Create an empty list for the current row

for j in range(cols):

element = int(input(f"Enter element at position [{i+1},{j+1}]: "))

row.append(element) # Append element to the current row

mat2.append(row)

# 1. Add the matrices

result_addition = add_matrices(mat1, mat2)

print("Matrix Addition:")

for row in result_addition:


print(row)

# 2. Transpose the first matrix

result_transpose = transpose_matrix(mat1)

print("\nTranspose of Matrix 1:")

for row in result_transpose:

print(row)

# 3. Multiply the matrices

result_multiplication = multiply_matrices(mat1, mat2)

print("\nMatrix Multiplication:")

for row in result_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:

You might also like