2014-10-17 73 views
-2

我想表明的答案在不同線路顯示在不同的線路

def f(k,e) : 
    if e==0 : 
     return '*' 
    return k*' '+'*'+e*' '+'*'+ f(k,e-1) 

結果:

*   * 
*   * 
    *  * 
    *  * 
    * * 
    * * 
     * 

回答

0

要添加換行符,你可以簡單地使用\n。但是,上面的代碼仍然不會按照指示創建ASCII「V」。

這裏有可能會接近你嘗試什麼樣的例子:

#create an ASCII 'V' with the indicated character and number of lines 
def buildV(lineCount, char): 
    lines = [] 
    currentLine = 1 
    while currentLine <= lineCount: 
     indent = currentLine * ' ' 
     if currentLine < lineCount: 
      gap = ((lineCount - currentLine) * 2 - 1) * ' ' 
      lines.append(indent + char + gap + char) 
     else: 
      lines.append(indent + char) 
     currentLine += 1 
    return '\n'.join(lines) 

#examples 
print(buildV(9, 'V')) 
print(buildV(6, '#')) 
print(buildV(2, '*')) 

輸出:

V    V 
    V    V 
    V   V 
    V   V 
    V  V 
     V  V 
     V V 
     V V 
     V 
#   # 
    #  # 
    #  # 
    # # 
    # # 
     # 
* * 
    * 
+0

哦,謝謝您的回答! – 2014-10-17 17:33:06

+0

但我需要使用遞歸和'\ n'不起作用! – 2014-10-17 17:34:08