# Tag Info

32

The NumPy Reference should be the first place you look when you have a problem like this. The operations you need are nearly always in there somewhere. And functions that you find while browsing the reference are sure to come in useful later in your NumPy career. For the first row, you could use numpy.arange and numpy.repeat: >>> np.repeat(np....

22

I believe the time complexity is $O(n^2)$, but I'd like to know for sure There's a general method for figuring out the time complexity for a piece of code, which is to annotate each line with the count of times it executes, and the average time it takes to execute, and then multiply and add. Before we do this it helps to rewrite the code so that just one ...

22

You can use NumPy module that's good with arrays and matrices. It has a built-in for exactly that purpose - import numpy as np np.rot90(image).tolist() With array manipulations, that's essentially same as performing matrix/array transpose and then flipping the rows - np.asarray(image).T[::-1].tolist() If the input is already an array, we can skip the ...

16

How about using Python built-ins to do the job? img = [[1, 2, 3], [10, 20, 30], [100, 200, 300]] list(reversed(list(zip(*img)))) [(3, 30, 300), (2, 20, 200), (1, 10, 100)]

8

Here are some things that may help you improve your program. Declare variables only where needed Old-style C required all variables to be declared at the top of the function in which they were used, but modern C has not required this for many years. For that reason, you can remove the declarations of i and j and incorporate them into the for loops instead,...

7

Reconsider ansi -ansi is equivalent to C89, which is many versions behind the current standard (C99 -> C11 -> C17). C99 is popular and will buy you some great language features. C17 is supported by gcc, though, so you should use that. Clean up your whitespace You should add one or two blank lines between each of your functions. Your tabs are non-uniform -...

7

I see a number of things that may help you improve your code. Pass by const reference where practical The first argument to MaxLocColumnWise is a Matrix but that causes the entire input matrix to be duplicated. Better would be to make it const Matrix & because it is not modified and it doesn't need to be duplicated. This is very likely the crux of ...

6

Testing: It's hard to notice problems in a long list of output like that. It's hard to track the state of the tempVec and determine the correct output for each case. Both these become harder if you have to come back to it later, making maintaining and changing the code changes difficult. It's much neater to split the testing up, and calculate a simple ...

6

You iterate through the same array twice (once while initializing and once while assigning values), you can do both inside the same loop. for (int i = 0; i < w; i++) { res[i] = new int[h]; for (int j = 0; j < h; j++) { res[i][j] = A[j][i]; } }

6

Lots of good comments already given. I'll just point out that you should most likely not be writing your own math primitives. It's easy to get wrong, it takes time away from actually creating what you're trying to create, you'll tear your hair out fixing hard to spot bugs and your code (contrary to what most people who write their own math primitives seem ...

6

Dimensions How big is your chess board, and is it square, or at least rectangular? First, you use range(len(board)) to determine the rows of the chess board, but then you use range(len(board[r])) for the columns, which means you can handle each row having a different number of columns! (Supporting a non-rectangular chess board would be a challenging ...

5

That's some nicely presented code. I found it very easy to read and understand. A vector of rows isn't the best structure for a matrix. The reason is that each vector has its storage elsewhere, so you lose locality of access. A better structure is a flat array (or vector) of elements, and a knowledge of the stride from one row to the next. (we can make ...

5

mat (const std::initializer_list & ini) You forgot to allocate any memory. Rule of 0/5 Your class should follow the rule of 5 which states you should define copy-constructor, copy-assignment operator, move-constructor, move-assignment operator and destructor if you define one of them. You are missing copy-assignment operator, move-constructor, and ...

5

The golden rule of I/O performance is never read a block twice. You're reading each block thousands of times. I made a thousand-row test file with records of about 2MB each: tr -dc '[:alnum:]' < /dev/urandom | fold -w2000000 | head -1000 > test.txt And modified the fps-building portion of your code thusly: #!/usr/bin/env python from prettyprinter ...

5

General - it might be better to create a matrix class and your own vector class in a namespace. Allow The Tools to Help You Improve the Code There are compiler settings that can help you improve your code, these can be specific the the c++ compiler you are using or they can be common. A common c++ compiler switch is -Wall which indicates a errors and ...

4

This is easy using numpy.roll, for example: zx = np.roll(x, 1) * (np.roll(x, 2) + np.roll(x, -1)) - x

4

Matrix(const std::vector<T> &, std::size_t rows, std::size_t cols); The first argument would better be accepted by-value, i.e. Matrix(std::vector<T> elements, std::size_t rows, std::size_t cols) : elements(std::move(elements)), rows(rows), cols(cols) {} This way you cover construction both from lvalues and rvalues (the temporary ...

4

Overview Sure this is one way to represent a Matrix. typedef vector<vector<double> > Matrix; The problem here is that there is no enforcement that these are rectangular. Your code makes the assumption they are rectangles and things will go very wrong if the assumption is wrong. You don't use encapsulation. Matrix add(Matrix a, Matrix b) ...

4

OverView I understand that it is common to use rows and cols in the constructor. BUT if you use it as part of the type information you can do some compile time checks that prevents illegal expressions. For example: In multiplications. You can check that the size of the matrices are correct for the multiplication at compile time. The down size is that you ...

4

Your code loops N x M x N times, where N is currently 424600 and M is 55. I don't think it's going to finish. I tried a couple of variations of your code, and the results are below. The version marked "original" is pretty true to your original code, except that I returned the results instead of storing them in a file. (So I could compare them against the ...

4

In the end, since this was only needed (for now) for $LU$ decomposition, I ended up ditching the lower/upper subclasses and went for the classical approach instead (as suggested by @harold), which is storing the lower and upper matrices of the decomposition in a single matrix, by taking advantage of the fact that $L$ is unit triangular:  \begin{...

4

It would be more efficient to use binary exponentiation. Suppose that you want to raise an n by n matrix to the $k^{th}$ power. The current method requires that you do a normal matrix multiplication $k-1$ times. This of course has complexity $k$ multiplied by $f(n)$, Where $f(n)$ is the complexity of a matrix multiplication ( This is usually $n^... 4 20+ percent faster using the stack for the extra buffer. Matrix Question Answer(1) Faster ------------------------------------------- 16 x 16 3.62 µsec 2.62 µsec 27.6 % 13 x 13 2.67 µsec 2.05 µsec 23.2 % 10 x 10 1.77 µsec 1.35 µsec 23.7 % 7 x 7 1.02 µsec 0.77 µsec 24.5 % 4 x 4 0.56 µsec 0.44 µsec ... 4 Barring any compiler heroics, you are computing n*n a total of$n^3\\$ times. You might want to cache that result. const int nn = n*n; B[j + n_times_i] is a linearly increasing address location, given that j increases by 1 for each middle loop, and and i increases once for each outer loop, which is n increases of j. Taking advantage of that, you can skip ...

4

nested methods Why do you nest the get_max_shape etcetera in the pad? There is no need to do this. get_max_shape Here you use recursion and a global variable. A simpler way would be to have a generator that recursively runs through the array, and yields the level and length of that part, and then another function to aggregate this results. That way you ...

3

There's a lot of code here to review, so this is likely not going to be a complete review. Data access I'll start with one of your questions: Is there a convenient way to get a single function that allows to set/get with a single function? As I understand this question (and what I was getting at in the comments) is that you want to get and set elements ...

3

Some general remarks: Don't use namespace std;, see for example Why is “using namespace std;” considered bad practice?. Don't put all the code into main(). Computing the determinant in a separate function increases the overall clarity of the program and makes it easier to add test cases. In addition, that gives you a function which can be reused in other ...

3

There's a lot that can be improved in your code, especially if you are using C++. The more advanced features of C++ actually help you organize your code better, help you write less code to do what you want, and remove a lot of tedium that you find in C-style code. Use proper names for variables and functions Names should accurately reflect what the purpose ...

3

Performance Here's where all the action happens: # Select the first r columns of u corresponding to the r principle Eigenvector of # MatrixForEigenvalues TRANSPOSE_NEW_EIGVEC = array(NEW_EIGVEC).real.T # Done for easy accessibility of matrix TRANSPOSE_MATRIX_U = array(NEW_U).real.T # Done for easy accessibility of matrix FINAL_ARRAY_EIGVAL = [] ...

3

Don't put everything into one big main() If you can separate out the reading of inputs and writing of results from the actual multiplications, then it will be easier to test the multiplication code separately. Avoid non-standard libraries Here we have "stdafx.h" and scanf_s that aren't part of standard C++. Ditch those and use the standard facilities (e....

Only top voted, non community-wiki answers of a minimum length are eligible