【问题标题】:Reason for result of output of Python codePython代码输出结果的原因
【发布时间】:2017-05-23 19:19:11
【问题描述】:

为什么 while 循环在打印帕斯卡三角形时执行的次数比预期的要多? 每次执行 while 循环时 x 增加 1 而 n 保持不变 我刚开始学习python 请帮忙

memo = {0:1}
def fac(n):
    if n not in memo:
        memo[n] = n*fac(n-1)
        return memo[n]
    else:
        return memo[n]

def pascal(x, space):
    while(x <= n):
        for j in range(space):
            print(" ", end = "")
        for i in range(0, x+1):
            print ( int(fac(x)/(fac(i)*fac(x-i))), end = " " )
        print("\n", end = "")
        x += 1
        space -= 1
        pascal(x, space)

n = eval(input())
space = n
x = 0
pascal(x, space)

【问题讨论】:

  • 备忘录与它有什么关系? memo的功能只是计算阶乘并将其分别存储在字典中@AzatIbrakov
  • 究竟什么是“多于预期”?
  • @gabrielbelini 请运行它并查看
  • 你可能应该使用factorial
  • 删除内部递归调用pascal(x, space) 就可以了

标签: python-3.x


【解决方案1】:

您正在使用两种方法来遍历 pascal 函数中的数字、while 循环和递归调用。你只需要其中之一。

保持while 循环:

def pascal(x, space):
    while(x <= n):
        for j in range(space):
            print(" ", end = "")
        for i in range(0, x+1):
            print ( int(fac(x)/(fac(i)*fac(x-i))), end = " " )
        print("\n", end = "")
        x += 1
        space -= 1

保持递归调用,将while 变成if

def pascal(x, space):
    if(x <= n):
        for j in range(space):
            print(" ", end = "")
        for i in range(0, x+1):
            print ( int(fac(x)/(fac(i)*fac(x-i))), end = " " )
        print("\n", end = "")
        x += 1
        space -= 1
        pascal(x, space)

给定 3 作为输入,两个版本都会打印以下内容:

   1
  1 1
 1 2 1
1 3 3 1

【讨论】:

  • 谢谢@legoscia
猜你喜欢
  • 2014-10-17
  • 2021-09-14
  • 2021-04-07
  • 1970-01-01
  • 1970-01-01
  • 2021-10-16
  • 1970-01-01
  • 2017-08-05
  • 1970-01-01
相关资源
最近更新 更多