带递归的模式(python)
所以我们被分配了一个程序,它要求两种符号,然后要求一个数字,这是图案的宽度。 例如: 对于奇数带递归的模式(python),python,recursion,Python,Recursion,所以我们被分配了一个程序,它要求两种符号,然后要求一个数字,这是图案的宽度。 例如: 对于奇数 string 1: * string 2: ^ width: 5 ***** ***^^ *^^^^ ***^^ ***** 我们应该对此使用递归 因此,我对如何使两个字符串交织感到困惑和困惑,这意味着我将如何使第二列具有***^^,我已经能够为此编写框架代码,这是它们之间的关系我无法做到的。下面的递归解决方案使用适当的fillchar: def pat(s1, s2, width, i=0):
string 1: *
string 2: ^
width: 5
*****
***^^
*^^^^
***^^
*****
我们应该对此使用递归
因此,我对如何使两个字符串交织感到困惑和困惑,这意味着我将如何使第二列具有***^^,我已经能够为此编写框架代码,这是它们之间的关系我无法做到的。下面的递归解决方案使用适当的
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)
******
****^^
**^^^^
^^^^^^
**^^^^
****^^
******
以下递归解决方案与适当的
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)
******
****^^
**^^^^
^^^^^^
**^^^^
****^^
******