1

我已经画了一个正面朝上的直角三角形,看起来像这样:

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

带代码:

row = 1
while row <= size:
    col = 1
    while col <= row:
        print chr, 
        col = col + 1

    print '' 

    row = row + 1
print ''

但我需要画一个看起来像这样的三角形:

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

我不完全确定如何去做。我知道它至少需要 2 个利用打印空间和字符的嵌套循环。要求仅使用 while 循环。

如果有人能阐明如何为我写这个,我将不胜感激。

4

4 回答 4

3

使用str.join

def solve(width):
    for i in xrange(width, 0, -1):
        print ' '.join([' ']*(width-i) + ['*']*i)
...         
>>> solve(5)
* * * * *
  * * * *
    * * *
      * *
        *
>>> solve(7)
* * * * * * *
  * * * * * *
    * * * * *
      * * * *
        * * *
          * *
            *
于 2013-11-08T04:29:50.830 回答
1

Edited to make rotate triangle, also came up with a better way of doing it

chr = "*"
size = 5
row = 1
while row <= size:
    col = size - row + 1
    while col <= size:
        print ' ', 
        col = col + 1
    col = 0
    while col <= size-row:
        print chr, 
        col = col + 1
    row = row + 1
    print ''
print ''
于 2013-11-08T04:28:50.783 回答
0
    size = 10
    def draw(n):
        if n<=size:
            draw(n+1)
            for i in range(n):
                print("#", end="")
            print(end= "\n")


    draw(0)
于 2022-03-02T10:38:38.767 回答
-1

使用最短

num = int(raw_input('Enter number :'))
for a in reversed(range(num+1)):
    print ' '*(num-a)+'*'*(a)

Enter number :7
*******
 ******
  *****
   ****
    ***
     **
      *
于 2017-10-28T17:44:09.127 回答