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

Unit 4 Python

Python notes
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)
24 views

Unit 4 Python

Python notes
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/ 17

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
Ans:

def sort_words_in_file(input_file, output_file):

try:

# Read words from the input file

with open(input_file, 'r') as infile:

words = infile.read().split()

# Convert words to lowercase and sort them

sorted_words = sorted(word.lower() for word in words)

# Write the sorted words to the output file

with open(output_file, 'w') as outfile:

for word in sorted_words:

outfile.write(word + '\n')

print(f'Sorted words have been written to {output_file}')

except FileNotFoundError:

print(f'The file {input_file} was not found.')

except Exception as e:

print(f'An error occurred: {e}')

# Example usage
input_file = 'source.txt' # Replace with your input file name

output_file = 'sorted_output.txt' # Replace with your desired output file name

sort_words_in_file(input_file, output_file)

# Opening a file for reading

with open('sorted_output.txt', 'r') as file:

content = file.read()

print(content)

output::

--------

source.txt

-----

Chintapaka

Dum

DuM

Sorted words have been written to sorted_output.txt

sorted_output.txt

------

chintapaka

dum #----->'D' converted into lower

dum #----->'D','M' converted into lower


2)

Ans:

# Open the file in write mode

f1 = open("output.txt", "w")

# Open the input file and get

# the content into a variable data

with open("file.txt", "r") as myfile:

data = myfile.read()

# For Full Reversing we will store the

# value of data into new variable data_1

# in a reverse order using [start: end: step],

# where step when passed -1 will reverse

# the string

data_1 = data[::-1]

# Now we will write the fully reverse

# data in the output1 file using

# following command

f1.write(data_1)

f1.close()

with open('output.txt', 'r') as file:

content = file.read()
print(content)

input:

-----

file.txt:- srk srk srk

vijaya vijaya vijaya

output:

-----

output.txt:-ayajiv ayajiv ayajiv

krs krs krs

3) python program to compute the number of characters, words and lines in a


file
Ans:

# Function to count number of characters, words, spaces and lines in a file

def counter(fname):

# variable to store total word count

num_words = 0

# variable to store total line count

num_lines = 0

# variable to store total character count

num_charc = 0

# variable to store total space count


num_spaces = 0

# opening file using with() method

# so that file gets closed

# after completion of work

with open(fname, 'r') as f:

# loop to iterate file

# line by line

for line in f:

# incrementing value of num_lines with each

# iteration of loop to store total line count

num_lines += 1

# declaring a variable word and assigning its value as Y

# because every file is supposed to start with a word or a character

word = 'Y'

# loop to iterate every

# line letter by letter

for letter in line:

# condition to check that the encountered character

# is not white space and a word


if (letter != ' ' and word == 'Y'):

# incrementing the word

# count by 1

num_words += 1

# assigning value N to variable word because until

# space will not encounter a word can not be completed

word = 'N'

# condition to check that the encountered character is a white space

elif (letter == ' '):

# incrementing the space

# count by 1

num_spaces += 1

# assigning value Y to variable word because after

# white space a word is supposed to occur

word = 'Y'

# loop to iterate every character

for i in letter:

# condition to check white space


if(i !=" " and i !="\n"):

# incrementing character

# count by 1

num_charc += 1

# printing total word count

print("Number of words in text file: ",

num_words)

# printing total line count

print("Number of lines in text file: ",

num_lines)

# printing total character count

print('Number of characters in text file: ',

num_charc)

# printing total space count

print('Number of spaces in text file: ',

num_spaces)

# Driver Code:

if __name__ == '__main__':

fname = 'File1.txt'
try:

counter(fname)

except:

print('File not found')

output::

-------

Number of words in text file: 10

Number of lines in text file: 4

Number of characters in text file: 33

Number of spaces in text file: 6

4.write a python program to create ,display, append, insert and reverse the
order of the items in the array
class ArrayManager:

def __init__(self):

# Initialize an empty list to represent the array

self.array = []

def display(self):

# Display the current items in the array

print("Current array items:", self.array)

def append(self, item):

# Append an item to the end of the array

self.array.append(item)

print(f"Appended '{item}' to the array.")


def insert(self, index, item):

# Insert an item at a specific index

if index < 0 or index > len(self.array):

print("Index out of bounds!")

return

self.array.insert(index, item)

print(f"Inserted '{item}' at index {index}.")

def reverse(self):

# Reverse the order of items in the array

self.array.reverse()

print("Reversed the array.")

def main():

manager = ArrayManager()

# Create the array

manager.append(1)

manager.append(2)

manager.append(3)

manager.display()

# Append new items

manager.append(4)

manager.append(5)

manager.display()

# Insert an item at index 1

manager.insert(1, 'a')

manager.display()
# Reverse the array

manager.reverse()

manager.display()

if __name__ == "__main__":

main()

output:
Appended '1' to the array.

Appended '2' to the array.

Appended '3' to the array.

Current array items: [1, 2, 3]

Appended '4' to the array.

Appended '5' to the array.

Current array items: [1, 2, 3, 4, 5]

Inserted 'a' at index 1.

Current array items: [1, 'a', 2, 3, 4, 5]

Reversed the array.

Current array items: [5, 4, 3, 2, 'a', 1]

5. Write a python program to create add, transpose and multiply two matrices
def create_matrix(rows, cols):

"""Create a matrix with user input."""

matrix = [] # Initialize an empty matrix

print(f"Enter the elements of the {rows}x{cols} matrix:")

for i in range(rows):

row = input(f"Row {i + 1}: ").split() # Prompt user for input and split it into a list
# Convert input strings to integers

row = list(map(int, row))

# Ensure the row has the correct number of columns

while len(row) != cols:

print(f"Please enter exactly {cols} elements.")

row = input(f"Row {i + 1}: ").split()

row = list(map(int, row))

matrix.append(row) # Add the validated row to the matrix

return matrix

def add_matrices(A, B):

"""Add two matrices."""

if len(A) != len(B) or len(A[0]) != len(B[0]):

raise ValueError("Matrices must have the same dimensions for addition.")

result = [] # Initialize an empty result matrix

# Perform element-wise addition

for i in range(len(A)):

result_row = [] # Initialize an empty row for the result


for j in range(len(A[0])):

result_row.append(A[i][j] + B[i][j]) # Add corresponding elements

result.append(result_row) # Add the row to the result matrix

return result

def transpose_matrix(matrix):

"""Transpose a matrix."""

transposed = [] # Initialize an empty matrix for the transposed result

# Create the transposed matrix

for i in range(len(matrix[0])): # Iterate over columns of the original matrix

transposed_row = [] # Initialize an empty row for the transposed matrix

for j in range(len(matrix)): # Iterate over rows of the original matrix

transposed_row.append(matrix[j][i]) # Append the element to the transposed row

transposed.append(transposed_row) # Add the transposed row to the transposed


matrix

return transposed

def multiply_matrices(A, B):

"""Multiply two matrices."""

if len(A[0]) != len(B):
raise ValueError("Number of columns in A must be equal to number of rows in B.")

result = [] # Initialize an empty result matrix

# Perform matrix multiplication

for i in range(len(A)):

result_row = [] # Initialize an empty row for the result

for j in range(len(B[0])):

sum_product = 0 # Initialize sum for the dot product

for k in range(len(B)): # Iterate through the columns of B

sum_product += A[i][k] * B[k][j] # Compute the dot product

result_row.append(sum_product) # Append the sum to the result row

result.append(result_row) # Add the result row to the result matrix

return result

def print_matrix(matrix):

"""Print a matrix."""

for row in matrix:

print(" ".join(map(str, row))) # Join elements in the row and print

def main():

# Create Matrix A
rows_A = int(input("Enter number of rows for Matrix A: "))

cols_A = int(input("Enter number of columns for Matrix A: "))

A = create_matrix(rows_A, cols_A)

# Create Matrix B

rows_B = int(input("Enter number of rows for Matrix B: "))

cols_B = int(input("Enter number of columns for Matrix B: "))

B = create_matrix(rows_B, cols_B)

# Print matrices

print("\nMatrix A:")

print_matrix(A)

print("\nMatrix B:")

print_matrix(B)

# Addition

if rows_A == rows_B and cols_A == cols_B:

sum_matrix = add_matrices(A, B)

print("\nA + B:")

print_matrix(sum_matrix)

else:

print("\nMatrices cannot be added due to dimension mismatch.")

# Transpose

transposed_A = transpose_matrix(A)
transposed_B = transpose_matrix(B)

print("\nTranspose of A:")

print_matrix(transposed_A)

print("\nTranspose of B:")

print_matrix(transposed_B)

# Multiplication

if cols_A == rows_B:

product_matrix = multiply_matrices(A, B)

print("\nA * B:")

print_matrix(product_matrix)

else:

print("\nMatrices cannot be multiplied due to dimension mismatch.")

if __name__ == "__main__":

main()

output:
Enter number of rows for Matrix A: 3

Enter number of columns for Matrix A: 3

Enter the elements of the 3x3 matrix:

Row 1: 1 2 3

Row 2: 4 5 6

Row 3: 7 8 9

Enter number of rows for Matrix B: 3


Enter number of columns for Matrix B: 3

Enter the elements of the 3x3 matrix:

Row 1: 1 2 3

Row 2: 4 5 6

Row 3: 7 8 9

Matrix A:

123

456

789

Matrix B:

123

456

789

A + B:

246

8 10 12

14 16 18

Transpose of A:

147

258

369
Transpose of B:

147

258

369

A * B:

30 36 42

66 81 96

102 126 150

You might also like