Question

In: Computer Science

I am trying to write a python code to create a function that returns all possible...

I am trying to write a python code to create a function that returns all possible dimensions (reshaping) for an input matrix, can someone explains the math and write a python code with explaining all the steps and give me a test cases, and please explain if there is more than one approach. so if we have 1*8 matrix we should return 1*8, 2*4,4*2,8*1

def reshaping(M) should return a n ORDERED list AND the all possible reshaped matrices

Solutions

Expert Solution

import numpy as np          #for using reshape() function to reshape matrix with each dimension

def reshaping(M):           #function definition
    m = len(M)              #calculating number of rows
    n = len(M[0])           #calculating number of columns
    elements = m*n          #calculating number of elements in the matrix

    '''so the main maths behind this is that all the factors of total elements in matrix
        will have a reshape possible starting from 1 to total elements
        so here we will loop all such factors and create a dimension from it
        after that we will reshape matrix for each dimension we added to the list'''

    dimensions = []         #to store all the dimensions possible for a matrix
    reshaped_matrices = []          #to store all the reshaped matrices
    for i in range(1, elements+1):
        if elements%i == 0:         #factor will completely divide total elements
            dimensions.append(f'{i}*{elements // i}')           #appending dimension to the list
            reshaped_matrices.append(M.reshape(i, elements//i))     #reshaping and appending
    return dimensions, reshaped_matrices        #returning the dimension list and reshaped matrices

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])         #testcase 1
M = arr.reshape(4,3)    #creating a sample matrix
dim, res = reshaping(M)     #calling the function
print(f'Ordered List of all possible dimensions: {dim}\n')          #printing ordered dimension list
for i in res:       #printing each reshaped matrix
    print(i, '\n')

Screenshot of output:


Related Solutions

This is my code for python. I am trying to do the fourth command in the...
This is my code for python. I am trying to do the fourth command in the menu which is to add an employee to directory with a new phone number. but I keep getting error saying , "TypeError: unsupported operand type(s) for +: 'dict' and 'dict". Below is my code. What am I doing wrong? from Lab_6.Employee import * def file_to_directory(File): myDirectory={}       with open(File,'r') as f: data=f.read().split('\n')    x=(len(data)) myDirectory = {} for line in range(0,199):      ...
this is my code in python I am trying to open a file and then print...
this is my code in python I am trying to open a file and then print the contents on my console but when i run it nothing prints in the console def file_to_dictionary(rosterFile): myDictionary={}    with open(rosterFile,'r') as f: for line in f: myDictionary.append(line.strip()) print(myDictionary)             return myDictionary    file_to_dictionary((f"../data/Roster.txt"))      
I am trying to create a function in JAVA that takes in an ArrayList and sorts...
I am trying to create a function in JAVA that takes in an ArrayList and sorts the values by their distance in miles in increasing order. So the closest (or lowest) value would be first. It does not need to output the values in anyway, but it should return them so they can be output elsewhere. Please try to use the stub class below. The code for the main class is not necessary. I am only really asking for the...
Using Python, I am trying to integrate 'iloc' into the line of code below? This line...
Using Python, I am trying to integrate 'iloc' into the line of code below? This line is replacing all the '1' values across my .csv file and is throwing off my data aggregation. How would I implement 'iloc' so that this line of code only changes the '1's integers in my 'RIC' column? patient_data_df= patient_data_df.replace(to_replace=[1], value ="Stroke") Thank you:)
I am trying to write a code in C for a circuit board reads in a...
I am trying to write a code in C for a circuit board reads in a temperature from a sensor on the circuit board and reads it onto a 7-segment LED display. How exactly would you code a floating 2 or 3 digit reading onto the LED display? I am stuck on this part.
Q: Using Python: Am trying to write a code that can be tested. Any assistance will...
Q: Using Python: Am trying to write a code that can be tested. Any assistance will be appreciated. Would want Help in understanding and solving this example from Data Structure & Algorithms (Computer Science) with the steps of the solution to better understand, thanks. The purpose of this assignment is the application of queues. A prime number is a positive integer other than 1 and is divisible only by 1 and itself. For example, 7 is a prime number because...
I am trying to write the code for an 8 bit adder in VHDL so that...
I am trying to write the code for an 8 bit adder in VHDL so that I can program it onto my Elbert V2 Spartan 3A FPGA Development Board, but I keep getting errors. Any ideas what I am doing wrong? library IEEE; use IEEE.STD_LOGIC_1164.ALL; entity adder8bit is Port ( a : in STD_LOGIC_VECTOR(7 downto 0); b : in STD_LOGIC_VECTOR(7 downto 0); cin : in STD_LOGIC; o : out STD_LOGIC_VECTOR(7 downto 0); cout : out STD_LOGIC); end adder8bit; architecture Behavioral...
I am trying to implement a search function for a binary search tree. I am trying...
I am trying to implement a search function for a binary search tree. I am trying to get the output to print each element preceding the the target of the search. For example, in the code when I search for 19, the output should be "5-8-9-18-20-19" Please only modify the search function and also please walk me through what I did wrong. I am trying to figure this out. Here is my code: #include<iostream> using namespace std; class node {...
Palindrome Javascript I am trying to write this javascript function to check if a number is...
Palindrome Javascript I am trying to write this javascript function to check if a number is Palindrome.. Palindrome means - a word, phrase, or sequence that reads the same backward as forward, e.g., madam or nurses run. This is the code i have, but it doesnt work. Code: let convertButton = document.getElementsByClassName("btn")[0]; let userInput = document.getElementById("number").value; let results = document.getElementById("result").value; convertButton.addEventListener("click", function (event) { event.preventDefault(); console.log(userInput); if (validatePalidrome(userInput)) document.getElementById("result").innerHTML = "true"; else document.getElementById("result").innerHTML = "false"; }); function validatePalidrome(numbers) { let...
Palindrome Javascript - NUMBERS I am trying to write this javascript function to check if a...
Palindrome Javascript - NUMBERS I am trying to write this javascript function to check if a number is Palindrome.. Palindrome means - a word, phrase, or sequence that reads the same backward as forward, e.g., 12321 This is the code i have, but it doesnt work. PLEASE MAKE SURE IT WORK BEFORE POST ANSWER, I GOT @ CODE THAT DID WORK BEFORE HTML JavaScript Palindrome Exercise rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css" /> Palindrome Enter a positive number: Is this a palindrome? No...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT