用python 实现矩阵乘法

#this is a project which calculate two cbue's multiply

class Cube (object):
	def __init__(self):
		self.cube = []
		self.line = int(raw_input('please input the number of lines:'))
		self.row = int(raw_input('please input the number of row:'))
	def value(self):
		tmp = []
		ltmp =0
		rtmp =0
		for r in range (0,self.row):
			for l in range (0,self.line):
				tmp.append(int(raw_input('input %d row %d line value: '% (rtmp,ltmp))))
				ltmp = ltmp+1
			self.cube.append(tmp)
			rtmp =rtmp+1
			tmp = []
			ltmp =0
	def show(self):
		print '%d row %d line: '% (self.row,self.line)
		print 'cube is :'
		print self.cube
	def multiply (self,other):
		if self.line != other.row :
			print 'can\'t do multiply!'
		else :
			cub = []
			result = []
			tmp = []
			for a in range (0,self.row):
				for b in range (0,other.line):
					for x in range (0,self.line):
						result.append(self.cube[a][x]*other.cube[x][b])
					tmp.append(sum(result))
					result =[]
				cub.append(tmp)
				tmp=[]
			print 'the result of multiply is :'
			print cub
cube1 = Cube()	
cube1.value()
cube1.show()
cube2 = Cube()
cube2.value()
cube2.show()
cube1.multiply(cube2)

首先我定义了一个Cube矩阵类:

Cube类里的第一个方法:__init__()

初始化矩阵大小

Cube类里的第二个方法:value()

对矩阵按先行后列方法进行赋值

Cube类里的第三个方法:multiply()

对两个矩阵进行相乘求结果

参数为乘数矩阵

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值