from mrjob.job import MRJob
from mrjob.step import MRStep
class MatrixMultiplication(MRJob):
def mapper(self, _, line):
# Read input line
matrix, i, j, value = line.split()
i, j, value = int(i), int(j), int(value)
# If it's from matrix A, send to appropriate column in result
if matrix == "A":
for k in range(2): # Assume B has 2 columns
yield (i, k), ("A", j, value)
# If it's from matrix B, send to appropriate row in result
elif matrix == "B":
for k in range(2): # Assume A has 2 rows
yield (k, j), ("B", i, value)
def reducer(self, key, values):
A_values = {}
B_values = {}
# Collect values
for matrix, index, value in values:
if matrix == "A":
A_values[index] = value
else:
B_values[index] = value
# Multiply and sum up
result = sum(A_values.get(k, 0) * B_values.get(k, 0) for k in range(2))
yield key, result
if __name__ == '__main__':
MatrixMultiplication.run()
ZnJvbSBtcmpvYi5qb2IgaW1wb3J0IE1SSm9iCmZyb20gbXJqb2Iuc3RlcCBpbXBvcnQgTVJTdGVwCgpjbGFzcyBNYXRyaXhNdWx0aXBsaWNhdGlvbihNUkpvYik6CgogICAgZGVmIG1hcHBlcihzZWxmLCBfLCBsaW5lKToKICAgICAgICAjIFJlYWQgaW5wdXQgbGluZQogICAgICAgIG1hdHJpeCwgaSwgaiwgdmFsdWUgPSBsaW5lLnNwbGl0KCkKICAgICAgICBpLCBqLCB2YWx1ZSA9IGludChpKSwgaW50KGopLCBpbnQodmFsdWUpCgogICAgICAgICMgSWYgaXQncyBmcm9tIG1hdHJpeCBBLCBzZW5kIHRvIGFwcHJvcHJpYXRlIGNvbHVtbiBpbiByZXN1bHQKICAgICAgICBpZiBtYXRyaXggPT0gIkEiOgogICAgICAgICAgICBmb3IgayBpbiByYW5nZSgyKTogICMgQXNzdW1lIEIgaGFzIDIgY29sdW1ucwogICAgICAgICAgICAgICAgeWllbGQgKGksIGspLCAoIkEiLCBqLCB2YWx1ZSkKCiAgICAgICAgIyBJZiBpdCdzIGZyb20gbWF0cml4IEIsIHNlbmQgdG8gYXBwcm9wcmlhdGUgcm93IGluIHJlc3VsdAogICAgICAgIGVsaWYgbWF0cml4ID09ICJCIjoKICAgICAgICAgICAgZm9yIGsgaW4gcmFuZ2UoMik6ICAjIEFzc3VtZSBBIGhhcyAyIHJvd3MKICAgICAgICAgICAgICAgIHlpZWxkIChrLCBqKSwgKCJCIiwgaSwgdmFsdWUpCgogICAgZGVmIHJlZHVjZXIoc2VsZiwga2V5LCB2YWx1ZXMpOgogICAgICAgIEFfdmFsdWVzID0ge30KICAgICAgICBCX3ZhbHVlcyA9IHt9CgogICAgICAgICMgQ29sbGVjdCB2YWx1ZXMKICAgICAgICBmb3IgbWF0cml4LCBpbmRleCwgdmFsdWUgaW4gdmFsdWVzOgogICAgICAgICAgICBpZiBtYXRyaXggPT0gIkEiOgogICAgICAgICAgICAgICAgQV92YWx1ZXNbaW5kZXhdID0gdmFsdWUKICAgICAgICAgICAgZWxzZToKICAgICAgICAgICAgICAgIEJfdmFsdWVzW2luZGV4XSA9IHZhbHVlCgogICAgICAgICMgTXVsdGlwbHkgYW5kIHN1bSB1cAogICAgICAgIHJlc3VsdCA9IHN1bShBX3ZhbHVlcy5nZXQoaywgMCkgKiBCX3ZhbHVlcy5nZXQoaywgMCkgZm9yIGsgaW4gcmFuZ2UoMikpCiAgICAgICAgeWllbGQga2V5LCByZXN1bHQKCmlmIF9fbmFtZV9fID09ICdfX21haW5fXyc6CiAgICBNYXRyaXhNdWx0aXBsaWNhdGlvbi5ydW4oKQ==