递归模式(python)

时间:2018-02-12 04:59:30

标签: python recursion

所以我们被分配了一个程序,它要求两种符号,然后要求一个数字,即模式的宽度。 例如:

string 1: *
string 2 :^
width : 4

****
**^^
^^^^
**^^
****

和奇数

string 1: *
string 2: ^
width: 5

*****
***^^
*^^^^
***^^
*****

我们应该为此

使用递归

所以我只是对如何使两个字符串编织感到困惑和困惑,这意味着如何让第二列有*** ^^,我已经能够为此编写帧代码了是他们之间的关系我不能做。

1 个答案:

答案 0 :(得分:3)

以下递归解决方案使用str.rjust(width[, fillchar])与适当的fillchar

def pat(s1, s2, width, i=0):
    # formula for the number of s2 ('^') in the i-th row
    x = 2 * (width//2 - abs(i - width//2))  # works for even and odd n
    if x >= 0:  # base case: negative number of s2
        print((s2 * x).rjust(width, s1))  # output row
        pat(s1, s2, width, i+1)  # recursive call

>>> s1 = '*'
>>> s2 = '^'
>>> pat(s1, s2, 4)
****
**^^
^^^^
**^^
****
>>> pat(s1, s2, 5)
*****
***^^
*^^^^
***^^
*****
>>> pat(s1, s2, 6)
******
****^^
**^^^^
^^^^^^
**^^^^
****^^
******