python - Attempting to transpose a matrix using python3 -
i know missing pieces produce matrix cannot seem find mistakes start.
i have 3 tasks.
1) show empty matrix like. 2) show original matrix(4x3). 3) transpose matrix 3x4.
import sys scanner import * def creatematrix(size): if size == 0: return [] else: return [0] + creatematrix(size -1) def printgrid(gridlist): row in gridlist: print (str(row)+"\n") def nrows(g): return len(g) def ncols(g): return len(g[0]) def printmatrix(g): in range(0,nrows,1): j in range(0,ncols,1): print("the original matrix is:",g[i][j]) print('') print('') def printmatrixtranspose(g): j in range(0,ncols,1): in range(0,nrows,1): print("the transposed matrix is:",g[i][j]) print('') print('') def readinput(filename,grid): s = scanner(filename) r = s.readtoken() while r != "": r = int(r) c = s.readint() v = s.readint() grid[r][c]=v r = s.readtoken() s.close() def main(): grid = creatematrix(5) in range(4): grid[i] = creatematrix(5) readinput(sys.argv[1],grid) printmatrixtranspose(g) main()
i keep getting error, not sure how fix it.
traceback (most recent call last): file "transpose.py", line 51, in <module> main() file "transpose.py", line 48, in main readinput(sys.argv[1],grid) file "transpose.py", line 37, in readinput r = int(r) typeerror: int() argument must string or number, not 'method'
if managing matrix list of lists, transposing quite simplying using list argument zip()
function, so:
x = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]] print x print map(list,zip(*x))
we map()
list()
function across output of zip
zip returns list of tuples, not list of lists.
the above prints:
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]] [[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]]
edit: error suggests code you've added doesn't match running. check file saved, , verify there brackets ()
after each call readtoken
.
Comments
Post a Comment