Matrix Multiplication

  • warning: realpath() [function.realpath]: SAFE MODE Restriction in effect. The script whose uid is 1005 is not allowed to access /tmp owned by uid 0 in /var/www/sites/sugree/codenone.com/subdomains/www/html/includes/file.inc on line 190.
  • warning: realpath() [function.realpath]: SAFE MODE Restriction in effect. The script whose uid is 1005 is not allowed to access /tmp owned by uid 0 in /var/www/sites/sugree/codenone.com/subdomains/www/html/includes/file.inc on line 190.

โจทย์ http://www.codenone.com/node96

รุ่น 1

def row(m,i):
    return m[i]
 
def col(m,j):
    return map(lambda x: x[j],m)
 
def mmul(a,b):
    c = []
    for i in range(len(a)):
        cr = []
        for j in range(len(b)):
            cr.append(reduce(lambda x,y: x+y,
                             map(lambda ix,iy: ix*iy,row(a,i),col(b,j))))
        c.append(cr)
    return c

รุ่น 2

def rows(m):
    for y in m:
        yield y
 
def cols(m):
    for j,y in enumerate(m):
        yield map(lambda x: x[j],m)
 
def mmul(a,b):
    c = []
    for i in rows(a):
        cr = []
        for j in cols(b):
            cr.append(reduce(lambda x,y: x+y,
                             map(lambda ix,iy: ix*iy,i,j)))
        c.append(cr)
    return c

รุ่น 3

def mmul(a,b):
    c = []
    for i in rows(a):
        c += [map(lambda j: reduce(lambda x,y: x+y,
                                   map(lambda ix,iy: ix*iy,i,j)),
                  cols(b))]
    return c

รุ่น 4

def mmul(a,b):
    return map(lambda i: map(lambda j: reduce(lambda x,y: x+y,
                                              map(lambda ix,iy: ix*iy,i,j)),
                             cols(b)),
               rows(a))

ตอนรัน

a = [[1,2],
     [3,4]]
b = [[1,0],
     [0,1]]
 
c = mmul(a,b)
print c

ย้าย Codenone

ประกาศย้าย Codenone ไปใช้ Forum ของ Blognone แทนครับ ตามไปตั้งกระทู้ต่อได้ที่ Codenone Forum (รายละเอียดอ่านจากกระทู้ ย้าย Codenone ไปรวมกับ Blognone)

กระทู้เก่าๆ จะย้ายตามไปในภายหลัง ตอนนี้ปิดการโพสต์กระทู้ไว้ เหลือไว้เฉพาะอ้างอิงเท่านั้น