递归重写函数

时间:2016-04-20 23:21:42

标签: python recursion

我试图以递归方式打印出一个空心方块。我无法弄清楚如何重新编写函数def hollowSquare()来进行递归调用 注意:我必须在hollowSquare函数中有3个参数用于此赋值,count用于跟踪我绘制的位置。

def validateInput():
    n =True
    while n != False:
        height = int(input("Please enter the height of you square (must be > 0): "))
        if height < 0:
            validateInput()
        else:
            symb = input("Please enter a character for your square:")

            return(height,symb)


def hollowSquare(height,symb,count):
    innerSquare = height -2
    print ('*' * height)
    for i in range(innerSquare):
        print ('*' + ' ' * innerSquare + '*')
    print ('*' * height)  







def main():
    height,symb = validateInput()
    count =0    
    hollowSquare(height,symb,count)


main()

1 个答案:

答案 0 :(得分:1)

count变量未在循环版本中使用,因此我要说的是&#34;循环计数器&#34;&#34;对于递归版本。您可以将其设置为默认参数并从0开始,这样就不必使用显式0调用它,如下所示。为函数提供一种方法来确定它是应该停止还是继续重复,请在if count < height-1: .. else:下面显示。如果没有时间停止,它会检查它是否是第一行,在这种情况下它会打印起始行。否则,它会打印其中一个中间行。然后是递归调用,它将再次执行该过程。当count < height-1不再为真时,它将打印结束行并停止重复。请注意,我已使用'*'替换了您的硬编码symb

我已经调用了每个函数进行测试。

def hollowSquare(height, symb, count=0):
    if count < height-1:
        if not count:
            print (symb * height)
        else:
            print (symb + ' ' * (height-2) + symb)
        hollowSquare(height, symb, count+1)
    else:
        print (symb * height)

hollowSquare(5, '*')

print('-----')

def hollowSquare(height,symb,count):
    innerSquare = height -2
    print ('*' * height)
    for i in range(innerSquare):
        print ('*' + ' ' * innerSquare + '*')
    print ('*' * height)

hollowSquare(5, '*', 0)
相关问题