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

Posted Hann Yang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python 用类重载乘法运算符计算和打印杨辉三角形相关的知识,希望对你有一定的参考价值。

类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]
>>> 

以上是关于Python 用类重载乘法运算符计算和打印杨辉三角形的主要内容,如果未能解决你的问题,请参考以下文章

python学习(打印九九乘法表,三角形)

Python 打印九九乘法表(正三角格式输出)

Python 打印九九乘法表(正三角格式输出)

韩顺平循序渐进学java.作业练习.用类打印乘法表

python如何打印九九乘法表

思考: 对于一个要重载的运算符而言,什么样的运算符应该用类成员函数重载,什么情况应该用友元函数重载??