On 17/10/12 09:13:57, rusi wrote: > On Oct 17, 10:22 am, Terry Reedy <tjre...@udel.edu> wrote: >> On 10/16/2012 9:54 PM, Kevin Anthony wrote: >> >>> I've been teaching myself list comprehension, and i've run across >>> something i'm not able to convert. >> >> list comprehensions specifically abbreviate the code that they are >> (essentially) equivalent to. >> >> res = [] >> for item in source: >> res.append(f(item)) >> res >> >> <==> >> >> [f(item) for item in source] >> >> Matrix multiplication does not fit the pattern above. The reduction is >> number addition rather than list appending. > > Dunno why you say that. Heres matrix multiply using list > comprehensions: > > from operator import add > def dot(p,q): return reduce(add, (x*y for x,y in zip(p,q))) > > def transpose(m): return zip(*m) > > def mm(a,b): return mmt(a, transpose(b)) > > def mmt(a,b): return [[dot(ra, rb) for rb in b] for ra in a] > > which can then be 'reduced' to a one-liner if that takes your fancy
I can golf it down to two lines without losing readability: def dot(p,q): return sum(x*y for x,y in zip(p,q)) def mm(a,b): return [[dot(ra, rb) for rb in zip(*b)] for ra in a] Hope this helps, -- HansM -- http://mail.python.org/mailman/listinfo/python-list