问题描述
因此,我们分配了一个程序,其中要求两种符号,然后要求一个数字,即图案的宽度。 例:
string 1: *
string 2 :^
width : 4
****
**^^
^^^^
**^^
****
对于奇数
string 1: *
string 2: ^
width: 5
*****
***^^
*^^^^
***^^
*****
我们应该为此使用递归
所以我只是对如何使两个字符串交织感到困惑和困惑,这意味着我将如何使第二列具有*** ^^,我已经能够为此编写框架代码,这就是关系他们之间我做不到。
1楼
以下递归解决方案将与适当的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)
******
****^^
**^^^^
^^^^^^
**^^^^
****^^
******