Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/vba/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 显示一个";“大”;基于输入n的三角形_Python - Fatal编程技术网

Python 显示一个";“大”;基于输入n的三角形

Python 显示一个";“大”;基于输入n的三角形,python,Python,到目前为止,我已经编写了一种基于用户输入打印三角形的方法 Input: 2 Output: * *** Input: 3 Output: * *** ***** 我的Python代码如下: row = int(input()) for i in range (1, row + 1): for j in range (1, row - i + 1): print (end=" ") for j in range (

到目前为止,我已经编写了一种基于用户输入打印三角形的方法

Input: 2
Output:
 *
***

Input: 3
Output:
  *
 ***
*****
我的Python代码如下:

row = int(input())

for i in range (1, row + 1):
      for j in range (1, row - i + 1):
            print (end=" ") 
      for j in range (i, 0, -1):
            print ("*", end = "")
      for j in range (2, i + 1):
            print ("*", end = "")
      print()
如何使用当前代码获得这种三角形

Input: 2
Output:
    *
   ***
 *  *  *
*********

Input: 3
            *
           ***
          *****
       *    *    *
      ***  ***  ***
     ***************
  *    *    *    *    *
 ***  ***  ***  ***  ***
*************************

我真的需要别人的帮助。我不知道如何处理这个问题。

这里有一个小算法,可以打印您想要的内容。它处理任意数量的行:

rows = 3
cols = rows * 2 - 1

# Draws one line of a single triangle (the dimensions are given by 'cols' and 'rows')
def printTriangleLine(line, newline = False):
    string = None
    if line < 0: string = " " * cols
    elif line == rows - 1: string = "*" * cols
    else:
        string = " " * (rows-(line+1))
        string += "*" * (line * 2 +1)
        string += " " * (rows-(line+1))

    print(string, end="")
    if newline: print()


# Big triangles are constituted of small triangles drawn with 'printTriangleLine' 
# They have the same dimensions then the little triangles

def main():
    #iterate the big rows
    for row in range(0, rows):
        # iterates the lines within each little triangle (small rows)
        for line in range(0, rows):
            # iterates the big columns
            for i in range(0, cols):
                # finds the blank triangles
                blank = row < rows - 1
                if blank: blank = i < rows - (row + 1) or i > rows + (row - 1)
                # prints adding a newline at the end of the last column
                printTriangleLine(-1 if blank else line, i==cols-1)

if __name__ == "__main__":
    main()

非常感谢您,@dspr!我刚刚开始学习Python,并且非常坚持这一点。再次感谢你!
            *            
           ***           
          *****          
       *    *    *       
      ***  ***  ***      
     ***************     
  *    *    *    *    *  
 ***  ***  ***  ***  *** 
*************************