我正在尝试编写一个函数,它打印出一个类似于2到9范围内的数字形状的领结。任何不在2到9范围内的东西都不应该打印出来。
例如,
>>> numberBowTie(5)
1 1
22 22
333 333
4444 4444
5555555555
5555555555
4444 4444
333 333
22 22
1 1
我尝试过的大多数练习问题,我没有遇到任何问题,但我在编码这个特殊问题时遇到了困难。我想过只编写八种不同的打印输出,但这太邋。了。间距必须用数学方法计算。
我做的关闭练习问题类似于这个问题
def arrowHead(n):
for x in range(n+1):
print ((' '*n)+(' *'*x))
n = n - 1
但它并没有帮助我。
答案 0 :(得分:3)
def numberBowTie(num):
for i in range(num):
# the idea is to iterate on i and when it's '1' to print only one time '1'
# then 2*num - 2 spaces and then to print one time '1' again.
# now do the same with i=2 only print '2' twice, 2*num - 4 spaces and then '2' twice again
# or in general:
#
# 1) str(i)*i == print a string of the number i -> i times
# 2) ' '* (2 * (num - i)) == print one space (2 * (num - i)) times
# 3) do the same as in 1)
#
print str(i)*i + ' '* (2 * (num - i)) + str(i)*i
for i in range(num):
# in the second loop we do the exact same calculation only in reverse order
print str(num-i)*(num-i) + ' '* (2 * i) + str(num-i)*(num-i)
numberBowTie(9)
<强>输出强>
1 1
22 22
333 333
4444 4444
55555 55555
666666 666666
7777777 7777777
88888888 88888888
999999999999999999
999999999999999999
88888888 88888888
7777777 7777777
666666 666666
55555 55555
4444 4444
333 333
22 22
1 1
对于ssm(在一个循环中):
def numberBowTie(num):
part1 = ''
part2 = ''
for i in range(num+1):
part1 = part1 + str(i)*i + ' '* (2 * (num - i)) + str(i)*i +'\n'
part2 = part2 + str(num-i)*(num-i) + ' '* (2 * i) + str(num-i)*(num-i) + '\n'
print part1 + part2
答案 1 :(得分:1)
print('\n'.join(map(lambda i: (' '*2*(9-i)).join([str(i)*i]*2),
range(0, 10) + list(reversed(range(10))))))
如果你喜欢简洁:)
编辑 - 这是另一个。我们的想法是首先构建图像的一个象限,然后反映它以构建其余部分。
def bowtie(n):
quadrant = [str(i)*i + " "*(n-i) for i in range(1, n+1)]
def mirror2(xs):
mirror = lambda xs: list(xs) + list(reversed(xs))
return mirror([''.join(mirror(x)) for x in xs])
return '\n'.join(mirror2(quadrant))