初學PYthon,課后題計算輸出楊輝三角任意位置的數值 ,比如第100000行,第999位,計算時間大概0.021秒,貼出來與大家分享下
from time import *
a = int(input("請輸入行號:"))
b = int(input("請輸入所在行的第幾位:"))
while b > a:
b = int(input("位數不能大于行號,請重新輸入所在行的第幾位:"))
ks = time()
if a <= 2 or b ==1 or b == a:
print("第" + str(a) + "第" + str(b) + "位數是:1")
elif b == 2 or b == a-1:
print("第" + str(a) + "第" + str(b) + "位數是:" + str(a - 1))
else:
n = a-b+1
x = n*(n+1)
y = 1
for i in range(2,b):
if i < b-1:
x = x*(n+i)
y = y*i
else:
y = y*i
print("第" + str(a) + "第" + str(b) + "位數是:" + str(x//y))
print(time()-ks)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/24822.html
標籤:其他開發語言
上一篇:if a !=[] 和 if len(a) 的區別?
下一篇:請問怎么解決啊
