0
How to write a matrix transpose and exponentiation program without numpy
8 ответов
+ 3
The easiest way (IMO) to do a standard transpose of a (list) matrix in Python without using numpy or another non-builtin library is to just use the unpack operator with the zip and map functions. Where unpacking the matrix into the zip function will handle the transposing and then you can map that back to a list matrix.
matrix = [[1, 2, 3],
[4, 5, 6]]
matrix = list(map(list, zip(*matrix)))
# matrix == [[1, 4], [2, 5], [3, 6]]
+ 2
ChaoticDawg, Per Bratthammar:
sure, appart the fact that zip() function may not be easy to understand for a beginner ^^ (OP profile show that he just started the Python courses ;P)
I guess that first explanation could be better to improve its coding skill ;)
+ 2
visph
True, they have just started the course here and may not understand or know the functions or * operator, but if the OP has matrix, transposing, numpy, knowledge etc they may have further knowledge of python then what they have completed in the courses here. Plus, they can always ask for an explanation of how it works, which I'm sure we can provide. 😉
And, yes if they don't know how to write the code to do it manually with their own function, then it should be done that way 1st for education purposes.
+ 2
visph ChaoticDawg Yes, it was more from my perspective...
I think as a beginner it’s important to learn how to solve the problem with basic loops, to understand how to think to solve the problem. At the same time there is interesting to see how you actually can use Python in a another way. Maybe it depends on the students objectives, how intresting he or she is to look into more advance solution. But to me it, it gave me a reminder....🙂
+ 1
Hi! If you have a matrix of right dimension, you can change the value in it. Otherwise you have to expand the lists, on element at a time with
myList.append(myElement)
L0 = [
[1, 2, 3],
[4, 5, 6]
] # 2 inner lists
->
L_new = [
[1, 4],
[2, 5],
[3, 6]
] # 3 inner lists
1) Create a structure for L_new = [[], [], []]
2) start fill L_new[0]
L_new[0].append(1)
L_new[0].append(4)
3) Go on with L_new[1] etc
Insted of append numbers, you generalize it with index, and get the element from maxtrix L0.
The code above is pseudo code. You have to translate it to Python, if course.
+ 1
ChaoticDawg Yes, it is a very easy and nice way to do it! 👍🏼
0
Show your attempt. Or just do it all by yourself! No one's helping you!
0
new_matrix = [[0 for i in range(len_y)] for j in range(len_x)]
for i in range(0,len_x):
for j in range(0,len_y):
new_matrix[i][j] = matrix[j][i]
return new_matrix