2016-04-20 133 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