Reputation: 61
I am in a quandary right now. This piece of code looks valid but no matter how many times I tried to change its syntax, it still gives me the same result.
Basically, my problem is that even though I've created a list-nested list n x n matrix, when I try to assign values to entries in a specific row, I get a TypeError i.e.
TypeError: 'tuple' object does not support item assignment
I'm using Python 2.7. I assume that it is my fault and not a bug of Python. I need clarification. Please try the code and tell me whether it works on your com, and if not, shed light on the problem, if you can. Thanks in advance.
Here is the code
import sys
class Matrix:
def __init__(self, n):
"""create n x n matrix"""
self.matrix = [[0 for i in range(n)] for i in range(n)]
self.n = n
def SetRow(self, i, x):
"""convert all entries in ith row to x"""
for entry in range(self.n):
self.matrix[i][entry] = x
def SetCol(self, j, x):
"""convert all entries in jth column to x"""
self.matrix = zip(*self.matrix)
self.SetRow(j, x)
self.matrix = zip(*self.matrix)
def QueryRow(self, i):
"""print the sum of the ith row"""
print sum(self.matrix[i])
def QueryCol(self, j):
"""print the sum of the jth column"""
self.matrix = zip(*self.matrix)
x = sum(matrix[j])
self.matrix = zip(*self.matrix)
print x
mat = Matrix(256) # create 256 x 256 matrix
with open(sys.argv[1]) as file: # pass each line of file
for line in file:
ls = line.split(' ')
if len(ls) == 2:
query, a = ls
eval('mat.%s(%s)' %(query, a))
if len(ls) == 3:
query, a, b = ls
eval('mat.%s(%s, %s)' % (query, a, b))
File creator script here:
file = open('newfile', 'w')
file.write("""SetCol 32 20
SetRow 15 7
SetRow 16 31
QueryCol 32
SetCol 2 14
QueryRow 10
SetCol 14 0
QueryRow 15
SetRow 10 1
QueryCol 2""")
file.close()
Upvotes: 4
Views: 213
Reputation: 1124010
zip()
returns tuples:
>>> zip([1, 2], [3, 4])
[(1, 3), (2, 4)]
Map them back to lists:
self.matrix = map(list, zip(*self.matrix))
Upvotes: 6