我试图编写一个函数,打印出一个蝴蝶结形状的数字,范围从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

但这对我没有帮助。

最佳答案

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

09-25 20:53