2016-04-20 90 views
0

我想递归地打印出一个空心正方形。我不知道如何重写函数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() 
+0

有''请输入''表示您不能轻易自动测试它。我希望学校会先教测试。 –

回答

1

count变量没有在循环使用的版本,所以我说这是什么意图是“循环计数”的递归版本。您可以将其设置为默认参数,并将其从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) 
+0

谢谢,清楚的解释。 – jjjjj