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

Python - 2

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Python - 2

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Assignment - 2

1. Python program to create a 8x8 matrix and fill it with a checkerboard pattern
(slice operator):

import numpy as np

def printcheckerboard(n):
print("Executed By Sneha Dewani - C34")
print("Checkerboard pattern:")

x = np.zeros((n, n), dtype=int)

x[1::2, ::2] = 1
x[::2, 1::2] = 1

for i in range(n):
for j in range(n):
print(x[i][j], end=" ")
print()

n=8
printcheckerboard(n)

Output:

2. Menu driven code for numpy array


● create using array() and arrange()
● sum of array
● sort array
● compare two arrays

import numpy as np

def create_array():
rows = int(input("Enter the number of rows: "))
cols = int(input("Enter the number of columns: "))
arr = np.array([[int(input(f"Enter element at position ({i},{j}): ")) for j in range(cols)] for i
in range(rows)])
print("Array created successfully:")
print(arr)
return arr

def sum_array(arr):
total_sum = np.sum(arr)
print("Sum of the array elements:", total_sum)

def sort_array(arr):
sorted_arr = np.sort(arr)
print("Sorted array:")
print(sorted_arr)

def compare_arrays(arr1, arr2):


if np.array_equal(arr1, arr2):
print("Arrays are equal.")
else:
print("Arrays are not equal.")

def main():
print("Executed By Sneha Dewani - C34")
while True:
print("\nMENU:")
print("1. Create Array")
print("2. Sum of Array")
print("3. Sort Array")
print("4. Compare Two Arrays")
print("5. Exit")
choice = input("Enter your choice: ")
if choice == '1':
array1 = create_array()
elif choice == '2':
sum_array(array1)
elif choice == '3':
sort_array(array1)
elif choice == '4':
array2 = create_array()
compare_arrays(array1, array2)
elif choice == '5':
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")

main()

Output:
3. Python program
● to read two matrices from user
● Perform matrix multiplication
● Display diagonal elements
● Check whether its a square matrix

def read_matrix(rows, cols):


matrix = []
print(f"Enter {rows} rows and {cols} columns for the matrix:")
for i in range(rows):
row = list(map(int, input().split()))
if len(row) != cols:
print(f"Error: Each row should have {cols} elements.")
return None
matrix.append(row)
return matrix

def multiply_matrices(matrix1, matrix2):


if len(matrix1[0]) != len(matrix2):
print("Error: Matrix multiplication not possible.")
return None

result = [[0 for _ in range(len(matrix2[0]))] for _ in range(len(matrix1))]


for i in range(len(matrix1)):
for j in range(len(matrix2[0])):
for k in range(len(matrix2)):
result[i][j] += matrix1[i][k] * matrix2[k][j]

return result

def display_diagonal(matrix):
if len(matrix) != len(matrix[0]):
print("Error: Not a square matrix.")
return

diagonal_elements = [matrix[i][i] for i in range(len(matrix))]


print("It is a square matrix")
print("Diagonal elements:")
print(diagonal_elements)
print("Executed By Sneha Dewani - C34")
rows1 = int(input("Enter the number of rows for matrix 1: "))
cols1 = int(input("Enter the number of columns for matrix 1: "))
matrix1 = read_matrix(rows1, cols1)

rows2 = int(input("Enter the number of rows for matrix 2: "))


cols2 = int(input("Enter the number of columns for matrix 2: "))
matrix2 = read_matrix(rows2, cols2)

if matrix1 and matrix2:


result_matrix = multiply_matrices(matrix1, matrix2)
if result_matrix:
print("Resultant matrix after multiplication:")
for row in result_matrix:
print(row)
display_diagonal(result_matrix)

Output:
4. Write a program which can run two threads simultaneously. One thread will print
odd numbers and another will print even numbers.

import threading
import time

def print_odd():
for i in range(1, 21, 2):
print(f'Odd: {i}')
time.sleep(1)

def print_even():
for i in range(2, 21, 2):
print(f'Even: {i}')
time.sleep(1)

if __name__ == "__main__":
print("Executed By Sneha Dewani - C34")
odd_thread = threading.Thread(target=print_odd)
even_thread = threading.Thread(target=print_even)

odd_thread.start()
even_thread.start()

odd_thread.join()
even_thread.join()

print("Both threads have finished.")

Output:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy