def get_range(self): while 1: # get starting range range_from = input("Range from :") # validate range valid_range1 = validate_num(range_from) if valid_range1: # if valid then get ending range range_from = int(range_from) range_to = input("Range to:") # validate ending range valid_range2 = validate_num(range_to) if valid_range2: range_to = int(range_to) # store start and end range in a list self.xrange = range(range_from, range_to) # pass list of range to function return self.xrange else: print("Invalid range") else: print("Enter valid range") # getting choice of user to continue ans = input("You want to continue..[y/n]") if ans == 'n' or ans == 'N': return "exit..."
def line_plotting(self): print( "1.Draw line charts of the financial data of Alphabet Inc. between October 3, 2016 to October 7, 2016" ) print("2. Exit") print() while True: try: print() # accept choice from user self.choice = input("Enter choice : ") # validate choice number valid_choice = validate_num(self.choice) if valid_choice: choice = int(self.choice) if choice == 1: # reading .csv file df = pd.read_csv('fdata.csv', sep=',', parse_dates=True, index_col=0) # plotting of fdata.csv file's financial data df.plot() # show figures plt.show() elif choice == 2: exit() else: print("Enter valid choice") else: print("Enter only numbers") except Exception as e: print(e)
def line_plotting(self): print( "1.plot two or more lines on same plot with suitable legends of each line." ) print("2. Exit") print() while True: try: print() # accept choice from user self.choice = input("Enter choice : ") # validate choice number valid_choice = validate_num(self.choice) if valid_choice: choice = int(self.choice) if choice == 1: print("Enter range to draw line 1:") print("x axix:") x1 = create_list(3) print("Y axix :") y1 = create_list(3) plt.plot(x1, y1, label="line 1") print("values of x:") print(*x1) print("values of y:") print(*y1) print("Enter range to draw line 2:") print("x axix:") x2 = create_list(3) print("Y axix:") y2 = create_list(3) plt.plot(x2, y2, label="line 2") print("values of x:") print(*x2) print("values of y:") print(*y2) # plot lines to the axes # set label for x axes plt.xlabel('x_axix') # set label for y axes plt.ylabel('y_axix') # title for plotting line plt.title('Two lines on same plot') plt.legend() # show the figure plt.show() elif choice == 2: exit() else: print("Enter valid choice") else: print("Enter only numbers") except Exception as e: print(e)
def probability_on_coin(self): print("1.View sample space " "\n" "2. probability of three heads, HHH") print("3.probability that you observe exactly one heads?") print("4.Given that you have observed at least one heads" "\n" "probability that you observe at least two heads") print("5.Exit") while 1: try: print( "---------------------------------------------------------------" ) choice = int(input("Enter choice :")) print( "---------------------------------------------------------------" ) # validating choice valid_choice = validate_num(choice) if valid_choice: if choice == 1: # display sample space print("Sample Space is : ", self.sample_space) elif choice == 2: # probability of exact three heads three_head = ProbabilityStatistics.get_three_heads( self.sample_space) print("Probability of three heads, HHH : ", three_head) elif choice == 3: # probability of exact one head one_head = ProbabilityStatistics.get_one_head( self.sample_space) print( "Probability that you observe exactly one heads : ", one_head) elif choice == 4: # probability of at least one head at_least_one_head = ProbabilityStatistics.at_least_one_head( self.sample_space) print("Observed at least one head : ", at_least_one_head) # probability of at least two head two_head = ProbabilityStatistics.get_two_head( self.sample_space) print( "Probability that you observe at least two heads : ", two_head) print("Final Probability of both : ", at_least_one_head / two_head) elif choice == 5: exit() else: print("Invalid choice") except Exception as e: print(e)
def line_plotting(self): print("1.Draw a line using given axis values taken from a text file") print("2. Exit") print() while True: try: print() # accept choice from user self.choice = input("Enter choice : ") # validate choice number valid_choice = validate_num(self.choice) if valid_choice: choice = int(self.choice) if choice == 1: # opening file with open("test.txt") as f: # read content from file data = f.read() data = data.split('\n') # get row 0 value to x axis x = [row.split(' ')[0] for row in data] # get row 1 value to y axis y = [row.split(' ')[1] for row in data] # plot data in x y axes plt.plot(x, y) # set label for x axes plt.xlabel('x_axix') # set label for y axes plt.ylabel('y_axix') # title for plotting line plt.title('sample line') # show the figure plt.show() elif choice == 2: exit() else: print("Enter valid choice") else: print("Enter only numbers") except Exception as e: print(e)
def line_plotting(self): print( "1.draw a line with suitable label in the x axis, y axis and a title" ) print("2. Exit") print() while True: try: print() # accept choice from user self.choice = input("Enter choice : ") # validate choice number valid_choice = validate_num(self.choice) if valid_choice: choice = int(self.choice) if choice == 1: print("Enter range to draw line:") get_xrange = Utility.get_range(self) # y range values thrice than x y = [value * 3 for value in get_xrange] print("values of x:") print(*get_xrange) print("values of y(thrice of x)") # plot lines to the axes plt.plot(get_xrange, y) # set label for x axes plt.xlabel('x_axix') # set label for y axes plt.ylabel('y_axix') # title for plotting line plt.title('line') # show the figure plt.show() elif choice == 2: exit() else: print("Enter valid choice") else: print("Enter only numbers") except Exception as e: print(e)
def line_plotting(self): print() print( "1.draw a line using given axis values with suitable label in the x axis , y axis and a title" ) print("2. Exit") print() while True: try: print() # accept choice from user self.choice = input("Enter choice : ") # validate choice number valid_choice = validate_num(self.choice) if valid_choice: choice = int(self.choice) if choice == 1: # x axis values x = [1, 2, 3] # y axis values y = [2, 4, 1] # plot lines to the axes plt.plot(x, y) # set label for x axes plt.xlabel('x_axis') # set label for y axes plt.ylabel('y_axis') # title for plotting line plt.title('line') # show the figure plt.show() elif choice == 2: exit() else: print("Enter valid choice") else: print("Enter only numbers") except Exception as e: print(e)
def pandas_operations(self): # list of programs print("21. Insert a new column in existing DataFrame") print("22. program to iterate over rows in a DataFrame") print("23. get list from DataFrame column headers") print("0. Exit") print() while True: try: print() # accept choice from user self.choice = input("Enter choice : ") # validate choice number valid_choice = validate_num(self.choice) if valid_choice: choice = int(self.choice) if choice == 21: print(self.df, "\n") # function to get insert new column in DataFrame new_col = UtilityClass.add_new_col_in_data_frame( self.df) print(new_col) elif choice == 22: # iterate over rows in DataFrame for index, row in self.df.iterrows(): print(row['name'], row['score']) elif choice == 23: # get list from DataFrame column headers print(list(self.df.columns.values)) elif choice == 0: exit() else: print("Enter valid choice") else: print("Enter only numbers") except Exception as e: print(e)
def standard_deviation(self): print("1. p(x < 40)") print("2. p(x > 21)") print("3. p(30 < x < 35)") print("4. Exit") while 1: choice = int(input("Enter choice : ")) valid_choice = validate_num(choice) if valid_choice: # get probability for p(x < 40) if choice == 1: x = 40 value_1 = ProbabilityStatistics.get_std_deviation1( self, x, self.mean, self.std_deviation) print("[area to the left of 2.5] : ", value_1) # get probability for p(x > 21) elif choice == 2: x = 21 value_2 = ProbabilityStatistics.get_std_deviation1( self, x, self.mean, self.std_deviation) print("[area to the left of -2.25] : ", value_2) # get probability for p(30 < x < 35) elif choice == 3: x = 30 value_3 = ProbabilityStatistics.get_std_deviation1( self, x, self.mean, self.std_deviation) print("[area to the left of 0] : ", value_3) x1 = 35 value_4 = ProbabilityStatistics.get_std_deviation1( self, x1, self.mean, self.std_deviation) print("[area to the left of 1.25] : ", value_4) # exiting elif choice == 4: exit() else: print("Invalid choice") else: print("Please enter valid choice")
def find_probability(self): print( "1. What is the probability that it's not raining and there is heavy traffic and I am not late?" ) print(" 2. What is the probability that I am late?") print( "3. Given that I arrived late at work, what is the probability that it rained that day? " ) print("4. Exit") while 1: choice = int(input("Enter choice for getting probability : ")) valid_choice = validate_num(choice) if valid_choice: if choice == 1: # getting probability that its not rain,heavy traffic,not late probability1 = ProbabilityStatistics.get_n_rain_traffic_n_late( self) print( "Probability for not rain and heavy traffic and not late : ", probability1) elif choice == 2: # getting probability that i am late probability2 = ProbabilityStatistics.get_late(self) print("Probability that I am late : ", probability2) elif choice == 3: # getting probability that late, rain and heavy traffic probability3 = ProbabilityStatistics.get_rain_traffic_late( self) print("Probability that it rained that day : ", probability3) elif choice == 4: exit() else: print("Invalid choice") else: print("Please enter valid choice")
def get_random_number(self): while 1: print("----------------------------------------------") choice = int(input("Enter your choice : ")) # validate choice valid_choice = validate_num(choice) if valid_choice: if choice == 1: # display interval from [2, 7] print(self.interval) elif choice == 2: # get random number from list of intervals random_number = ProbabilityStatistics.random_number(self, self.interval) print("Random number from Interval : ", random_number) # calculating probability of random number probability = ProbabilityStatistics.random_probability(self, self.interval, random_number) print("Probability of random number is : ", probability) elif choice == 3: exit() else: print("Invalid choice") else: print("Enter choice in number")
def numpy_operations(self): # list of program print() print("21. concatenate two 2-dimensional arrays") print("22. make an array immutable (read-only)") print( "23. create an array of (3, 4) shape, multiply every element value by 3 and display the new array" ) print("24. convert a NumPy array into Python list structure") print( "25. convert a NumPy array into Python list structure with output as precision 3" ) print( "26. suppresses the use of scientific notation for small numbers in numpy array." ) print("27. program to how to add an extra column to an numpy array") print("28. remove specific elements in a numpy array") print("0. Exit") print( "--------------------------------------------------------------------------------------" ) while True: try: print() # accept choice from user self.choice = input("Enter choice : ") # validate choice number valid_choice = validate_num(self.choice) if valid_choice: choice = int(self.choice) if choice == 21: arr1 = np.array([[1, 2, 3], [4, 5, 6]]) print("Array 1:") print(arr1) arr2 = np.array([[7, 8, 9], [10, 11, 12]]) print("Array 2:") print(arr2) arr3 = np.concatenate((arr1, arr2), axis=1) print("Concatenated array :") print(arr3) elif choice == 22: arr = np.arange(10) # set this to false lack the data and make it read only arr.flags.writeable = False print("Test whether array is read only") # try to change value of immutable array arr[0] = 5 elif choice == 23: arr = np.arange(1, 13).reshape(3, 4) print("array of (3, 4) shape:") print(arr) # iterate over array and openflags as read write for x in np.nditer(arr, op_flags=['readwrite']): # each element is multiply with 3 # x[...] is 0d so x[:] could not work here x[...] = 3 * x print("multiplied every element value by 3") print(arr) elif choice == 24: arr = np.arange(8).reshape(4, 2) print("original array :" "\n", arr) # convert numpy array into python list structure print("List is : " "\n", arr.tolist()) elif choice == 25: # These options determine the way floating point numbers, # arrays and other NumPy objects are displayed. np.set_printoptions(precision=3) arr = np.array([ 0.26153123, 0.52760141, 0.5718299, 0.5927067, 0.7831874, 0.69746349, 0.35399976, 0.99469633, 0.0694458, 0.54711478 ]) # convert array to python list print("Original array : ", arr.tolist()) print("Values with precision 3 : ", np.array(arr)) elif choice == 26: arr = np.array([ 1.60000000e-10, 1.60000000e+00, 1.20000000e+03, 2.35000000e-01 ]) print(arr) # If True, always print floating point numbers using fixed point notation np.set_printoptions(suppress=True, precision=3) print(arr) elif choice == 27: arr1 = np.array([[10, 20, 30], [40, 50, 60]]) print("Original array:" "\n", arr1) arr2 = np.array([[100], [200]]) print("After appending :" "\n", np.append(arr1, arr2, axis=1)) elif choice == 28: arr = np.array( [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]) print("Original array :" "\n", arr) index = [1, 4, 5] # delete specific element from array print("Delete 1st, 4th, 5th element:" "\n", np.delete(arr, index)) elif choice == 0: exit() else: print("Enter valid choice") else: print("Enter only numbers") except Exception as e: print(e)
def numpy_operations(self): # list of programs print( "1. convert a list of numeric value into a one-dimensional NumPy array" ) print("2. 3x3 matrix with values ranging from 2 to 10") print( "3. create a null vector of size 10 and update sixth value to 11") print("4. reverse an array (first element becomes last).") print("5. create a 2d array with 1 on the border and 0 inside") print( "6. program to add a border (filled with 0's) around an existing array" ) print("7. create a 8x8 matrix and fill it with a checkerboard pattern") print("8. convert a list and tuple into arrays") print("9. program to append values to the end of an array") print( "10.find the real and imaginary parts of an array of complex numbers" ) print("0. Exit") print() while True: try: print() # accept choice from user self.choice = input("Enter choice : ") # validate choice number valid_choice = validate_num(self.choice) if valid_choice: choice = int(self.choice) if choice == 1: list1 = [12.23, 13.32, 100, 36.32] print("Original List is : ", list1) # function to convert list into NumPy array arr = np.array(list1) print("1D NumPy array : ", arr) elif choice == 2: # create array within range and reshape it 3x3 matrix = np.arange(2, 11).reshape(3, 3) print(matrix) elif choice == 3: # create vector of 11 zero's vector = np.zeros(11) print("Null Vector : ", vector) vector[5] = 11 print("Update sixth value to 11 : ", vector) elif choice == 4: arr = np.arange(12, 38) print("original : ", arr) # reverse array print("reverse : ", arr[::-1]) elif choice == 5: # create 5x5 array with one's value arr = np.ones((5, 5)) print("Original array : " "\n", arr) print("array with 1 on the border and 0 inside") # slicing on array arr[1:-1, 1:-1] = 0 print(arr) elif choice == 6: # create array 3x3 with all 1's arr = np.ones((3, 3)) print(arr) # add border filled with 0's around existing array arr = np.pad(arr, pad_width=1, mode='constant', constant_values=0) print(arr) elif choice == 7: arr = np.zeros((8, 8), dtype=int) # fill checkerboard pattern with 1 at every 2 row , 2 col arr[1::2, ::2] = 1 # fill checkerboard pattern with 1 at every 2 row, 2 col arr[::2, 1::2] = 1 print(arr) elif choice == 8: list1 = [1, 2, 3, 4, 5, 6, 7, 8] print("List : ", list1) # convert any type of input data into array print("Array : ", np.asarray(list1)) tuple1 = ([8, 4, 6], [1, 2, 3]) print("Tuple : ", tuple1) print("Array : ", np.asarray(tuple1)) elif choice == 9: arr = [10, 20, 30] print("Original array : ", arr) # append values at end of array arr = np.append(arr, [[40, 50, 60], [70, 80, 90]]) print("After append : ", arr) elif choice == 10: value1 = np.sqrt([1 + 0j]) value2 = np.sqrt([0 + 1j]) print("Original value1 : ", value1) print("Original value2 : ", value2) value3 = value1 + value2 print("Real part : ", value3.real) print("Imaginary part : ", value3.imag) elif choice == 0: exit() else: print("Enter valid choice") else: print("Enter only numbers") except Exception as e: print(e)
def pandas_operations(self): # list of programs print("1. create and display a 1-D array-like object containing an array of data using Pandas module") print("2. convert a Panda module Series to Python list and it's type") print("3. program to add, subtract, multiple and divide two Pandas Series") print("4. program to get the powers of an array values element-wise") print("5. create and display a DataFrame from a specified dictionary data which has the index labels") print("6. display a summary of the basic information about a specified Data Frame and its data.") print("7. program to get the first 3 rows of a given DataFrame") print("8. program to select the 'name' and 'score' columns from the given DataFrame. ") print("9. select the specified columns and rows from a given data frame." "Select 'name' and 'score' columns in rows 1, 3, 5, 6 from the given data frame") print("10. select the rows where the number of attempts in the examination is greater than 2. ") print("0. Exit") print() while True: try: print() # accept choice from user self.choice = input("Enter choice : ") # validate choice number valid_choice = validate_num(self.choice) if valid_choice: choice = int(self.choice) if choice == 1: n = int(input("How many element you want to add:")) if validate_num(n): num = int(n) # 1D labeled array holding integer type data data = UtilityClass.series_data(self, num) print(data) else: print("Please enter numeric value") elif choice == 2: n = input("How many element you want to add:") if validate_num(n): num = int(n) # getting series of data from pandas module data = UtilityClass.series_data(self, num) print("Pandas Series : ""\n", data) # type of series print("Type of series : ", type(data)) # convert series data into python list and display type print("Converted python list : ", data.tolist()) print("Type of python list : ", type(data.tolist())) else: print("Please enter numeric value") elif choice == 3: n = input("How many element you want to add:") if validate_num(n): num = int(n) # getting 1st series of data from pandas module data1 = UtilityClass.series_data(self, num) print("First pandas series : ") print("Pandas Series 1:""\n", data1) print("New series : ") # getting 1st series of data from pandas module data2 = UtilityClass.series_data2(self, num) print("Second pandas series : ") print("Pandas Series 2:""\n", data2) add = UtilityClass.series_addition(data1, data2) print("Addition:""\n", add) sub = UtilityClass.series_subtract(data1, data2) print("Subtraction:""\n", sub) mul = UtilityClass.series_multiplication(data1, data2) print("Multiplication:""\n", mul) div = UtilityClass.series_division(data1, data2) print("Division:""\n", div) else: print("Please enter numeric value") elif choice == 4: power = UtilityClass.get_power() print("Power of array value to element wise:") print(power) elif choice == 5: # get data frame for specified data df = UtilityClass.get_data_frame() print(df) elif choice == 6: df = UtilityClass.get_data_frame() print("Summary of basic information about specified data frame") # summary of data frame print(df.info()) elif choice == 7: df = UtilityClass.get_data_frame() print("data frame :") print(df, "\n") print("First 3 rows of data frame:") print(df.iloc[:3]) elif choice == 8: df = UtilityClass.get_data_frame() # getting name and score column from DataFrame print(df[['name', 'score']]) elif choice == 9: df = UtilityClass.get_data_frame() print(df, "\n") print("specified column and row from given DataFrame""\n") # getting specific column and row from DataFrame print(df.iloc[[1, 3, 5, 6], [0, 1]]) elif choice == 10: df = UtilityClass.get_data_frame() # get specific row from subset of rows print(df.ix[[1, 3, 5], ['name', 'score']]) elif choice == 0: exit() else: print("Enter valid choice") else: print("Enter only numbers") except Exception as e: print(e)
def pandas_operations(self): # list of programs print("11. count the number of rows and columns of a DataFrame") print("12. select the rows where the score is missing, i.e. is NaN. ") print( "13. select the rows where number of attempts in the examination is less than 2" " and score greater than 15. ") print("14. change the score in row 'd' to 11.5") print( "15. calculate the sum of the examination attempts by the students. " ) print( "16. calculate the mean score for each different student in DataFrame. " ) print( "17. append a new row 'k' to data frame with given values for each column." "Now delete the new row and return the original DataFrame. ") print( "18. sort the DataFrame first by 'name' in descending order, then by 'score' in ascending order" ) print( "19. replace the 'qualify' column contains the values 'yes' and 'no' with True and False. " ) print("20. delete the 'attempts' column from the DataFrame") print("0. Exit") print() while True: try: print() # accept choice from user self.choice = input("Enter choice : ") # validate choice number valid_choice = validate_num(self.choice) if valid_choice: choice = int(self.choice) if choice == 11: df = UtilityClass.get_data_frame() print(df, "\n") # get row count from DataFrame rows = len(df.axes[0]) # get column count from DataFrame cols = len(df.axes[1]) print("Total rows: " + str(rows)) print("Total cols: " + str(cols)) elif choice == 12: df = UtilityClass.get_data_frame() print(df, "\n") print("rows where the score is missing:" "\n") # get rows where score value is missing print(df[df['score'].isnull()]) elif choice == 13: df = UtilityClass.get_data_frame() print(df, "\n") # get rows where exam attempt is less than 2 and score greater than 15 print(df.ix[[9], ['name', 'score']]) elif choice == 14: df = UtilityClass.get_data_frame() print(df, "\n") # change the score of row 'd' to 11.5 df.loc['d', 'score'] = 11.5 print(df) elif choice == 15: df = UtilityClass.get_data_frame() # get sum of examination attempts print("sum of attempts : ", df['attempts'].sum()) elif choice == 16: df = UtilityClass.get_data_frame() print(df) # calculating mean value for each student print("Mean for each student: ", df['score'].mean()) elif choice == 17: df = UtilityClass.get_data_frame() # original DataFrame print("original DataFrame:" "\n") print(df, "\n") # change data in DataFrame data = UtilityClass.change_in_data_frame(df) print("After delete : " "\n", data) elif choice == 18: df = UtilityClass.get_data_frame() print(df, "\n") # sort name column in descending order df = df.sort_values(by=['name'], ascending=False) print("Desc by Name") print(df) print("Asc by score") # sort score data in ascending order df = df.sort_values(by=['score'], ascending=True) print(df) elif choice == 19: df = UtilityClass.get_data_frame() # replacing value of qualify column from yes - True and no - False df['qualify'] = df['qualify'].map({ 'yes': True, 'no': False }) print(df) elif choice == 20: df = UtilityClass.get_data_frame() print(df) print("\n" "After deleting attempts column:" "\n") # delete column df.pop('attempts') print(df) elif choice == 0: exit() else: print("Enter valid choice") else: print("Enter only numbers") except Exception as e: print(e)
def numpy_operations(self): # list of program print() print("11. find the number of elements of an array, length of one array element""\n" " in bytes and total bytes consumed by the elements") print() print("12. find common values between two arrays") print() print("13. find the set difference of two arrays. The set difference will return the sorted,""\n" " unique values in array1 that are not in array2.") print() print("14. find the set exclusive-or of two arrays. Set exclusive-or will return the sorted,""\n" " unique values that are in only one (not both) of the input arrays. ") print() print("15. compare two arrays using numpy") print() print("16. save a NumPy array to a text file") print() print("17. create a contiguous flattened array") print() print("18. change the data type of an array") print() print("19. create a 3-D array with ones on a diagonal and zeros elsewhere.") print() print("20. program to create an array which looks like below array") print(np.array([[0, 0, 0], [1, 0, 0], [1, 1, 0], [1, 1, 1]])) print() print("0. Exit") print("--------------------------------------------------------------------------------------") while True: try: print() # accept choice from user self.choice = input("Enter choice : ") # validate choice number valid_choice = validate_num(self.choice) if valid_choice: choice = int(self.choice) if choice == 11: # array declaration arr = np.array([10, 20, 30, 40, 50], dtype=float) # get size of element print("Number of element : ", arr.size) # get length of element print("Length of 1 element : ", arr.itemsize) # get total bytes consumed by elements of array print("Total bytes consumed by elements : ", arr.nbytes) elif choice == 12: arr1 = np.array([10, 20, 30, 40, 50]) print("Array 1: ", arr1) arr2 = np.array([15, 25, 10, 35, 30]) print("Array 2: ", arr2) print("Common values : ", np.intersect1d(arr1, arr2)) elif choice == 13: arr1 = np.array([0, 10, 60, 40, 20, 80]) print("Array 1: ", arr1) arr2 = np.array([10, 30, 40, 50, 70, 90]) print("Array 2: ", arr2) # getting set difference between two arrays print("Set difference between two arrays: ", np.setdiff1d(arr1, arr2)) elif choice == 14: arr1 = np.array([0, 10, 20, 40, 60, 80]) print("Array 1: ", arr1) arr2 = np.array([10, 30, 40, 50, 70]) print("Array 2: ", arr2) print("set exclusive-or of two arrays : ", np.setxor1d(arr1, arr2)) elif choice == 15: arr1 = np.array([1, 2]) print("Array 1: ", arr1) arr2 = np.array([3, 4]) print("Array 2: ", arr2) print("Array 1 < Array 2 : ", np.less(arr1, arr2)) print("Array 1 <= Array 2 : ", np.less_equal(arr1, arr2)) print("Array 1 > Array 2 : ", np.greater(arr1, arr2)) print("Array 1 >= Arrays 2 : ", np.greater_equal(arr1, arr2)) elif choice == 16: a = np.arange(0, 10, 1) # save array in text file np.savetxt("array.txt", a[:], fmt="%d") print("Array saved in array.txt file") # open file to read f = open("array.txt", 'r') # read file print(f.read()) elif choice == 17: arr = np.array([[1, 2, 3], [4, 5, 6]]) print(arr) # contiguous flattened array arr_new = np.ravel(arr) print("Contiguous Flattened array : ", arr_new) elif choice == 18: arr1 = np.array([1, 2, 3]) print("Data type of array : ", arr1.dtype) # change data type of an array new_arr = arr1.astype(float) print("Data type of array after change : ", new_arr.dtype) elif choice == 19: # 3x3 array of 0 with 1 on diagonal (Identity matrix) x = np.eye(3) print(x) elif choice == 20: def get_pattern(matrix, row, col): # iterate over rows for r_count in range(0, row): # iterate over cols for c_count in range(0, col): # if row 1 or more and col less than row print 1 if r_count > 0 and c_count < r_count: print("1", end=" ") else: # print zero's as it is print(matrix[r_count][c_count], end=" ") print() arr = np.array([[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]) r = 4 c = 3 # function call to get above pattern get_pattern(arr, r, c) elif choice == 0: exit() else: print("Enter valid choice") else: print("Enter only numbers") except Exception as e: print(e)