避免在程序中使用 "if" 语句绘制数字

2024-10-03 19:31:23 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是一个绘制数字树的程序,但我无法避免“if”语句

# -*- coding: cp1252 -*-
import sys
def xmasTree():
    centre=35
    inicial=1
    level=input("¿Triangle height? \n\t")
    for height in range (inicial,level+1): 
        for index in range(1,centre-height):
            sys.stdout.write(' ') 
        sys.stdout.write(str(inicial)) 
        for index in range(inicial+1,height): 
            sys.stdout.write(str(index))
        for index in range(height,inicial,-1):
            sys.stdout.write(str(index))
        if height>1:
            sys.stdout.write('1')
        sys.stdout.write('\n')
xmasTree()

*编辑:我终于找到了我想要的。显然我没有正确地解释自己。无论如何,谢谢大家!在

以下是正确的代码:

^{pr2}$

以及正确的输出:

                         1
                        121
                       12321
                      1234321
                     123454321
                    12345654321
                   1234567654321
                  123456787654321
                 12345678987654321

Tags: inforindexifstdoutsys绘制range
2条回答
height = 5
inicial = 2    
for l in range(initial, height):
     line = ''.join( 
                    str( max(l-i, i-l)+1 ) for i in range(2*l+1)
               )
     # {:^35} centers a string within 35 characters, look up python string formatting
     print( '{:^35}'.format(line) )

输出

^{pr2}$

递归函数:

def xmasTree(n,v=0):
    if n > 0:
        xmasTree(n-2, v+1)
        print " " * v + "".join(str(x%10) for x in range(n))
xmasTree(31)

相关问题 更多 >