Skip to content

Latest commit

 

History

History
149 lines (120 loc) · 3.13 KB

打印三角形.md

File metadata and controls

149 lines (120 loc) · 3.13 KB

格式输出

正向打印

编写一个函数,给出参数n,n为正整数,上下三角两种打印方式,要求数字必须对齐

                            1
                         2  1
                      3  2  1
                   4  3  2  1
                5  4  3  2  1
             6  5  4  3  2  1
          7  6  5  4  3  2  1
       8  7  6  5  4  3  2  1
    9  8  7  6  5  4  3  2  1
10  9  8  7  6  5  4  3  2  1

方法一

利用99乘法表的形式,但是么有对齐

def triangle(n=12):
    for i in range(1,n+1):
        for j in range(n,0,-1):
            print(j,end=" " if j !=1 else '\n') if i >= j else print(" ",end=" ")
triangle()

                      1
                    2 1
                  3 2 1
                4 3 2 1
              5 4 3 2 1
            6 5 4 3 2 1
          7 6 5 4 3 2 1
        8 7 6 5 4 3 2 1
      9 8 7 6 5 4 3 2 1
    10 9 8 7 6 5 4 3 2 1
  11 10 9 8 7 6 5 4 3 2 1
12 11 10 9 8 7 6 5 4 3 2 1

可以再修改下

def triangle(n=12):
    for i in range(1,n+1):
        for j in range(n,0,-1):
            print(j,end=" " if j !=1 else '\n') if i >= j else print(" " *len(str(j)) ,end=" ")
triangle()

                         1
                       2 1
                     3 2 1
                   4 3 2 1
                 5 4 3 2 1
               6 5 4 3 2 1
             7 6 5 4 3 2 1
           8 7 6 5 4 3 2 1
         9 8 7 6 5 4 3 2 1
      10 9 8 7 6 5 4 3 2 1
   11 10 9 8 7 6 5 4 3 2 1
12 11 10 9 8 7 6 5 4 3 2 1

方法二

右对齐方式

def triangle1(n=12):
    line = " ".join((str(i) for i in range(n,0,-1)))
    length = len(line)
    for i in range(1,n+1):
        print("{:>{}}".format(" ".join(str(k) for k in range(i,0,-1)),length))
triangle1()

继续优化

def triangle3(n=12):
    line =[str(x) for x in range(n,0,-1)]
    g = " ".join(line)
    length = len(g)
    for i in range(1,n+1):
        print("{:>{}}".format(" ".join(line[-i:]),length))
triangle3()

或者直接用字符串

def triangle(n=12):
    condition = [10**i for i in range(1,len(str(n))+1)]
    print(condition)
    line = [ str(i) for i in range(n,0,-1)]
    strr = " ".join(line)
    width = len(strr)
    start = 1
    step = 2
    for x in range(1,n+1):
        print("{:>{}}".format(strr[-start:],width))
        if (x+1) in condition:
            step += 1
        start += step
triangle()

倒着打印

def rtriangle(n=12):
    line = " ".join((str(x) for x in range(n,0,-1)))
    print(line)
    for i,j in enumerate(line):
        if j == " ":
            print(" "*(i-1),line[i:])

rtriangle()

12 11 10 9 8 7 6 5 4 3 2 1
   11 10 9 8 7 6 5 4 3 2 1
      10 9 8 7 6 5 4 3 2 1
         9 8 7 6 5 4 3 2 1
           8 7 6 5 4 3 2 1
             7 6 5 4 3 2 1
               6 5 4 3 2 1
                 5 4 3 2 1
                   4 3 2 1
                     3 2 1
                       2 1
                         1