Python - 2
Python - 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[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:
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 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
return result
def display_diagonal(matrix):
if len(matrix) != len(matrix[0]):
print("Error: Not a square matrix.")
return
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()
Output: