From d4e1f44d69561a743d0366900765a7d2c7769b87 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=AB=98=E7=BA=A7=E4=BA=91=E8=84=91=E7=A0=94=E5=8F=91?= =?UTF-8?q?=E5=B7=A5=E7=A8=8B=E5=B8=88?= <153692773@qq.com> Date: Tue, 14 Mar 2023 16:44:15 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20'tri.py'?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tri.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 tri.py diff --git a/tri.py b/tri.py new file mode 100644 index 0000000..9ab57ef --- /dev/null +++ b/tri.py @@ -0,0 +1,15 @@ +def triangles(x, y): + if y == 1 or y == x: # y=1或y=x时,函数返回值为1 + return 1 + else: + z = triangles(x-1, y-1) + triangles(x-1, y) # y为其他值时的递推公式 + return z +if __name__ == "__main__": + n = int(input("请输入杨辉三角的行数:")) + for i in range(1, n+1): # 输出n行 + for j in range(0, n-i+1): + print(" ", end=" ") + for j in range(1, i+1): + # 调用递归函数,输出第i行的第j个值 + print("%6d " %(triangles(i, j)), end=" ") + print() \ No newline at end of file