zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Python 用类重载乘法运算符计算和打印杨辉三角形

Python计算 打印 运算符 重载 乘法 杨辉三角
2023-09-14 09:01:28 时间

类class: 

>>> class Yh():
	def __init__(self,n=None):
		self.data = [1]
		if n!=None: self.data=Yh()*n
	def __repr__(self):
		return f'{self.data}'
	def __mul__(self,n):
		self.data = [1]
		while n>1:
			n-=1
			self.data.append(0)
			self.data=[sum(z) for z in zip(self.data,self.data[::-1])]
		return self.data
	__rmul__ = __mul__
	def List(n):
		i=0
		while i<n:
			i+=1
			print(Yh(i))

			
>>> Yh()
[1]
>>> Yh(2)
[1, 1]
>>> Yh(3)
[1, 2, 1]
>>> Yh(6)
[1, 5, 10, 10, 5, 1]
>>> Yh(13)
[1, 12, 66, 220, 495, 792, 924, 792, 495, 220, 66, 12, 1]
>>> 

测试:

>>> def test(func, n, out=True):
	from time import time
	start = time()
	if not out:
		t=(func(n))
	else:
		for i in range(1,n+1):
			print(f'Y({i:>2}) = {func(i)}')
	print(time()-start)

>>> test(Yh,15)
Y( 1) = [1]
Y( 2) = [1, 1]
Y( 3) = [1, 2, 1]
Y( 4) = [1, 3, 3, 1]
Y( 5) = [1, 4, 6, 4, 1]
Y( 6) = [1, 5, 10, 10, 5, 1]
Y( 7) = [1, 6, 15, 20, 15, 6, 1]
Y( 8) = [1, 7, 21, 35, 35, 21, 7, 1]
Y( 9) = [1, 8, 28, 56, 70, 56, 28, 8, 1]
Y(10) = [1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
Y(11) = [1, 10, 45, 120, 210, 252, 210, 120, 45, 10, 1]
Y(12) = [1, 11, 55, 165, 330, 462, 462, 330, 165, 55, 11, 1]
Y(13) = [1, 12, 66, 220, 495, 792, 924, 792, 495, 220, 66, 12, 1]
Y(14) = [1, 13, 78, 286, 715, 1287, 1716, 1716, 1287, 715, 286, 78, 13, 1]
Y(15) = [1, 14, 91, 364, 1001, 2002, 3003, 3432, 3003, 2002, 1001, 364, 91, 14, 1]
0.1680755615234375
>>>
>>> test(Yh,1000,False)
0.2420802116394043
>>> test(Yh,2000,False)
1.3822360038757324
>>> test(Yh,3000,False)
4.064407110214233
>>>

副产品

除了像函数一样使用外,还能用乘法表示项数,也可以直接列表:

>>> Yh(11)
[1, 10, 45, 120, 210, 252, 210, 120, 45, 10, 1]
>>> Yh()*12
[1, 11, 55, 165, 330, 462, 462, 330, 165, 55, 11, 1]
>>> 12*Yh()
[1, 11, 55, 165, 330, 462, 462, 330, 165, 55, 11, 1]
>>>
>>> triangle = Yh()
>>> 6 * triangle
[1, 5, 10, 10, 5, 1]
>>> triangle * 13
[1, 12, 66, 220, 495, 792, 924, 792, 495, 220, 66, 12, 1]
>>> triangle *= 5
>>> triangle
[1, 4, 6, 4, 1]
>>>
>>> Yh.List(10)
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
[1, 6, 15, 20, 15, 6, 1]
[1, 7, 21, 35, 35, 21, 7, 1]
[1, 8, 28, 56, 70, 56, 28, 8, 1]
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
>>>