以下是绘制数字树的程序,但我无法避免使用“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()
*编辑:最后我找到了我想要的东西。显然我没有正确解释自己。无论如何,谢谢大家!
这是正确的代码:
# -*- coding: cp1252 -*-
import sys
def xmasTree():
centre=35
sep=1
initial=1
level=input("¿Triangle height? \n\t")
for height in range (1,level+1):
for index in range(1,centre-height):
sys.stdout.write(' ')
sys.stdout.write(str(sep))
for index in range(initial+1,height+1):
sys.stdout.write(str(index))
for index in range(height+1,initial+1,-1):
sys.stdout.write(str(index-2))
sys.stdout.write('\n')
正确的输出:
1
121
12321
1234321
123454321
12345654321
1234567654321
123456787654321
12345678987654321
答案 0 :(得分:1)
递归函数:
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)
答案 1 :(得分:0)
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) )
<强>输出强>
212
32123
4321234
543212345