Python 尝试递归生成数字模式的新手

Python newbie trying to recursively generate a pattern of numbers

我需要编写一个函数来生成这些模式:

>>> pattern(1)
1
>>> pattern(2)
 1
121
 1
>>> pattern(3)
  1
 121
  1
12321
  1
 121
  1

这是我试过的:

def pattern(n):
    if n>=1:
        pattern(n-1)
        print(n,end='')
        pattern(n-1)

然后我尝试使用以下方法对其进行迭代:

>>>for i in range(3):
        pattern(i)
        print()

1
121

谁能帮我理解这个概念?

您需要将某种缩进传递给递归调用。每个递归调用需要打印 整行 ,而不仅仅是中间行的一部分。

所以对于 2,您要打印:

  • 1 的模式,缩进一次。
  • 数字 1、2 和 1,未缩进。
  • 1 的模式,缩进一次。

但是对于 3,您想要:

  • 2 的模式,缩进一次,见上文。
  • 数字 1 and 2 and 3 and 2 and 1,没有缩进。
  • 2 的模式,缩进一次,见上文。

然后递归调用每传递一次缩进就加一,递归为0时结束递归:

def pattern(num, indent=0):
    if not num:
        return
    pattern(num - 1, indent + 1)
    print(' ' * indent, end='')
    print(''.join(map(str, range(1, num))) + 
          ''.join(map(str, range(num, 0, -1))))
    pattern(num - 1, indent + 1)

演示:

>>> pattern(1)
1
>>> pattern(2)
 1
121
 1
>>> pattern(3)
  1
 121
  1
12321
  1
 121
  1
>>> pattern(4)
   1
  121
   1
 12321
   1
  121
   1
1234321
   1
  121
   1
 12321
   1
  121
   1