2017-04-03 41 views
0

我正在使用嵌套循環創建一個反轉三角形,並以任何字符量輸入。例如,如果輸入8,我的三角應該是這個樣子使用嵌套循環繪製三角形

xxxxxxxx 
xxxxxxx 
    xxxxxx 
    xxxxx 
    xxxx 
    xxx 
     xx 
     x 

我的代碼目前包括以下什麼,但輸出是不是我所期待的。

row = 1 
while row <= size: 
    # Output a single row 
    col = size - row + 1 
    while col <= size: 
     # Output the drawing character 
     print(end=' ') 

     # The next column number 
     col = col + 1 
    col = 0 
    while col <= size - row: 
     print(drawingChar, end=' ') 
     col = col + 1 
    row = row + 1 
    print() 
print() 

輸出:

x x x x x x x x 
    x x x x x x x 
    x x x x x x 
    x x x x x 
    x x x x 
     x x x 
     x x 
     x 

我敢肯定,我搞砸了次要的東西與我的<= size或山坳地方。所有的輸入是讚賞。

+0

的[反向倒置在python星號三角形]可能重複(HTTP:/ /stackoverflow.com/questions/19034814/reverse-upside-down-asterisk-triangle-in-python) – davedwards

+0

@downshift我看到那篇文章,並從這個答案中拿了一些東西,但即時通訊仍然把它指向等邊三角形 – Astonishing

+0

好的抱歉,一個沒有幫助。嘗試在第二個'while'循環中從'end'參數中刪除字符:'print(drawingChar,end ='')' – davedwards

回答

1
>>> def foo(n): 
... for i in range(n): 
...  print((" "*i) + ("x"*(n-i))) 
... 
>>> foo(8) 
xxxxxxxx 
xxxxxxx 
    xxxxxx 
    xxxxx 
    xxxx 
    xxx 
     xx 
     x 

編輯:

由於OP是要求嵌套循環溶液,在這裏它是:

>>> def foo(n): 
... out = "" 
... for i in range(n): 
...  for _ in range(i): 
...   out += " " 
...  for _ in range(n-i): 
...   out += "x" 
...  out += "\n" 
... print(out) 
... 
>>> foo(8) 
xxxxxxxx 
xxxxxxx 
    xxxxxx 
    xxxxx 
    xxxx 
    xxx 
     xx 
     x 
+0

我需要以嵌套循環的方式做到這一點 – Astonishing

+0

@令人驚訝的是,然後將我的解決方案轉換爲使用嵌套循環,但是,通常沒有必要這樣做。 – pkacprzak

+0

我在一個介紹python類,並且必須使用嵌套循環,我完全不知道你給我意味着什麼。我認爲我提供的代碼非常接近我試圖完成的工作 – Astonishing