Home | Reviews | GUIpedia | Forum | Fun500


ksrpython
I'm getting started with Python by writing some matrix arithmetic functions. Here is my addition function - my question is what is a nicer, more pythony way of doing it? def madd (m1, m2): if (len(m1) != len(m2)) or (len(m1[0]) != len(m2[0])): print "matrices cannot be added as they are not the same size" exit() m3 = copy.deepcopy(m1) for row in range(len(m1[0])): for column in range(len(m1)): m3[row][column] += m2[row][column] return m3
2010-10-061:43 AM

ksrRe:python
I've cracked it: m3 = [[m1[row][col] + m2[row][col] for col in range(len(m1[0]))] for row in range(len(m1))]
2010-10-065:29 PM

Other


2021 Brandon Cornell