Question 01 of 03

Menu-Driven NumPy Array Operations

Using the NumPy module, write a menu-driven Python program to perform: a. Create an array filled with 1's. b. Find maximum and minimum values from an array. c. Dot product of 2 arrays. d. Reshape a 1-D array to a 2-D array.

C++
import numpy as np

def numpy_menu():
    while True:
        print("\n" + "=" * 45)
        print("          NUMPY OPERATIONS MENU")
        print("=" * 45)
        print("1. Create an array filled with 1's")
        print("2. Find maximum and minimum values in an array")
        print("3. Dot product of 2 arrays")
        print("4. Reshape a 1-D array to 2-D array")
        print("5. Exit")
        print("=" * 45)
        
        choice = input("Enter your choice (1-5): ").strip()
        
        if choice == '1':
            rows = int(input("Enter number of rows: "))
            cols = int(input("Enter number of columns: "))
            ones_arr = np.ones((rows, cols), dtype=float)
            print(f"\nArray filled with 1's ({rows}x{cols}):\n{ones_arr}")
            
        elif choice == '2':
            raw = input("Enter array elements separated by spaces: ")
            arr = np.array([float(x) for x in raw.split()])
            print(f"Array: {arr}")
            print(f"Maximum Value: {np.max(arr)}")
            print(f"Minimum Value: {np.min(arr)}")
            
        elif choice == '3':
            raw1 = input("Enter first vector elements (e.g. 1 2 3): ")
            raw2 = input("Enter second vector elements (e.g. 4 5 6): ")
            v1 = np.array([float(x) for x in raw1.split()])
            v2 = np.array([float(x) for x in raw2.split()])
            if len(v1) != len(v2):
                print("Error: Arrays must have the same length for dot product!")
            else:
                dot_res = np.dot(v1, v2)
                print(f"\nVector 1: {v1}")
                print(f"Vector 2: {v2}")
                print(f"Dot Product (v1 . v2) = {dot_res}")
                
        elif choice == '4':
            raw = input("Enter elements for 1-D array: ")
            arr1d = np.array([int(x) for x in raw.split()])
            r = int(input("Enter target rows: "))
            c = int(input("Enter target columns: "))
            if r * c != len(arr1d):
                print(f"Error: Cannot reshape array of size {len(arr1d)} into ({r}x{c})!")
            else:
                arr2d = arr1d.reshape(r, c)
                print(f"\nOriginal 1-D Array:\n{arr1d}")
                print(f"Reshaped 2-D Array ({r}x{c}):\n{arr2d}")
                
        elif choice == '5':
            print("Exiting NumPy menu. Goodbye!")
            break
        else:
            print("Invalid choice! Please choose between 1 and 5.")

if __name__ == "__main__":
    numpy_menu()
Question 1 of 3