Python
Python
#4. Create 2D array of size mXn with random number between p & q.
p=int(input("Enter a lower limit:"))
q=int(input("Enter an upper limit:"))
m=random.randint(p,q)
n=random.randint(p,q)
print("So the required matrix",m,"x",n)
import numpy as np
k = []
for i in range(m):
row = []
for j in range(n):
q = float(input("Enter element : "))
row.append(q)
k.append(row)
array = np.array(k)
print("The required array is: \n",array)
Enter element : 1
Enter element : 2
Enter element : 3
Enter element : 4
Enter element : 5
Enter element : 6
Enter element : 7
Enter element : 8
Enter element : 9
Array:
[[1. 2. 3.]
[4. 5. 6.]
[7. 8. 9.]]
Enter no of rows: 3
Enter no of columns: 3
Enter element : 1
Enter element : 2
Enter element : 3
Enter element : 4
Enter element : 5
Enter element : 6
Enter element : 7
Enter element : 8
Enter element : 9
[1 2 3 4]
[[11 22]
[33 44]]
[1 2 3 4 5]
#9. Write a Python program to sort a given array of shape 2 along the
first axis, last axis and on the flattened array
import numpy as np
a=np.array([[11,22] , [33,44]])
print("Sorting on first axis")
print(np.sort(a,axis=0))
print("Sorting on last axis")
print(np.sort(a, axis=1))
print("Sort the flattened array")
print(np.sort(a,axis=None))
while True:
print("*****Menu*****")
print("1. Addition of two 2D arrays")
print("2. Multiplication of two 2D arrays")
print("3. Transpose of a 2D array")
print("4. Inverse of a 2D array")
print("5. Multiply 2D array by scalar")
print("6. Exit")
if choice == 1:
print("Addition of arrays:")
res = np.add(q, p)
print(res)
elif choice == 2:
print("Multiplication of arrays:")
result = np.multiply(q, p)
print(result)
elif choice == 3:
print("Transpose of the first array:")
res = np.transpose(q)
print(res)
print("Transpose of the second array:")
res = np.transpose(p)
print(res)
elif choice == 4:
print("Inverse of the first array:")
res = np.linalg.inv(q)
print(res)
print("Inverse of the second array:")
res = np.linalg.inv(p)
print(res)
elif choice == 5:
sc = float(input("Enter a scalar value: "))
print("Multiplying the first array by scalar:")
result = np.multiply(q, sc)
print(result)
print("Multiplying the second array by scalar:")
result = np.multiply(p, sc)
print(result)
elif choice == 6:
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")
*****Menu*****
1. Addition of two 2D arrays
2. Multiplication of two 2D arrays
3. Transpose of a 2D array
4. Inverse of a 2D array
5. Multiply 2D array by scalar
6. Exit
Addition of arrays:
[[ 6 8]
[10 12]]
*****Menu*****
1. Addition of two 2D arrays
2. Multiplication of two 2D arrays
3. Transpose of a 2D array
4. Inverse of a 2D array
5. Multiply 2D array by scalar
6. Exit