0

对于我的编程课,我必须创建一个程序来创建一个“金字塔”(在 IDLE 中),如下所示:

              1 
            1 2 1 
          1 2 4 2 1 
        1 2 4 8 4 2 1 
      1 2 4 8 16 8 4 2 1 

它会在2**(row)哪里row = 0(最初)。它在for循环中使用。

n它提出了一个问题,即对于大于 5的值,输出不会像预期的那样出现。

到目前为止,这是我的代码:

def pyramid(n):
   rows, num, x, numbers, space_length, i_length = 0, '', 0, {}, 0, 0
   for rows in range(n):
      x = int(len(num) / 2)
      y = str(2**rows) + ' '
      num = num[0:x + 1] + y + num[x - 1 :]
      numbers[rows + 1] = num
   space_length = int(len(numbers[n]) / 2)
   for i in numbers:
      i_length = int(space_length - (len(numbers[i]) / 2))
      numbers[i] = (' ' * i_length) + numbers[i]
      print(numbers[i])

def main():    #I have to use the function of main() because my teacher requires it.
   n = int(input("Enter an integer greater than 0: "))
   if type(n) != int or n <= 0:
      raise TypeError("N must be an integer greater than 0.")
   pyramid(n)

main()

这是我得到的输出:

>>> 
Enter an integer greater than 0: 10
                      1 
                    1 2 1 
                  1 2 4 2 1 
                1 2 4 8 4 2 1 
              1 2 4 8 16 8 4 2 1 
           1 2 4 8 1632 16 8 4 2 1 
         1 2 4 8 1632 64 2 16 8 4 2 1  #The 2 should be 32; space between 16 and 32.
      1 2 4 8 1632 64128 64 2 16 8 4 2 1    #Same thing again; spacing messes up.
   1 2 4 8 1632 64128256 28 64 2 16 8 4 2 1 
1 2 4 8 1632 64128256512 56 28 64 2 16 8 4 2 1 

如果有人可以帮我解决这个问题,那就太好了。谢谢!

4

3 回答 3

1

这是你想要的?

def pyramid(n):
   rows, num, x, numbers, space_length, i_length = 0, '', 0, {}, 0, 0
   for rows in range(n):
      x = int(len(num) / 2)
      y = str(2**rows) + '  '
      num = num[0:x + 2:] + y + num[x - 1:]
      numbers[rows + 1] = num
   space_length = int(len(numbers[n]) / 2)
   for i in numbers:
      i_length = int(space_length - (len(numbers[i]) / 2))
      numbers[i] = (' ' * i_length) + numbers[i]
      print(numbers[i])

def main():    #I have to use the function of main() because my teacher requires it.
   n = int(input("Enter an integer greater than 0: "))
   if type(n) != int or n <= 0:
      raise TypeError("N must be an integer greater than 0.")
   pyramid(n)

main()

输出:

                                1  
                             1  2  1  
                          1  2  4  2  1  
                       1  2  4  8  4  2  1  
                   1  2  4  8  16  8  4  2  1  
                1  2  4  8  16  32  6  8  4  2  1  
            1  2  4  8  16  32 64  32  6  8  4  2  1  
        1  2  4  8  16  32 64  128  4  32  6  8  4  2  1  
    1  2  4  8  16  32 64  128 256  28  4  32  6  8  4  2  1  
1  2  4  8  16  32 64  128 256 512  56  28  4  32  6  8  4  2  1  
于 2012-12-05T03:07:15.057 回答
1

The code shown below works fine for the values of n that I tested (1 to 20). Note, in Python 2.7 and later the format '{:{}}' says to print two items, the first being the value to print, and the second the field width to print it in. (2.6 may require field numbers, eg '{0:{1}}', which I haven't tested.) The expression 2**min(x, 2*i-x) is used to generate sequences like 1 2 4 2 1 and 1 2 4 8 16 32 64 128 64 32 16 8 4 2 1 that count up and then back down. Array f holds field widths corresponding to the largest numbers in the table, ie those in the bottom line. sum(f[:n-i]) is the sum of the field widths prior to the first number printed in a line. Note, the print ... , form prints a separating space and does not advance to a new line. Some example output is shown after the code.

def pyramid(n):
    f = [1+len(str(2**min(i, 2*n-i-2))) for i in range(1+2*n)]
    for i in range(n):
        for x, w in zip(range(1+2*i), [sum(f[:n-i])]+f[n-i:]):
            print '{:{}}'.format(2**min(x, 2*i-x), w-1),
        print

pyramid(5)
pyramid(10)
for i in range(21):
    pyramid(i)

Example output for n=15:

                                                     1
                                               1     2    1
                                          1    2     4    2    1
                                     1    2    4     8    4    2    1
                                1    2    4    8    16    8    4    2    1
                           1    2    4    8   16    32   16    8    4    2   1
                       1   2    4    8   16   32    64   32   16    8    4   2   1
                   1   2   4    8   16   32   64   128   64   32   16    8   4   2   1
               1   2   4   8   16   32   64  128   256  128   64   32   16   8   4   2  1
            1  2   4   8  16   32   64  128  256   512  256  128   64   32  16   8   4  2  1
         1  2  4   8  16  32   64  128  256  512  1024  512  256  128   64  32  16   8  4  2  1
      1  2  4  8  16  32  64  128  256  512 1024  2048 1024  512  256  128  64  32  16  8  4  2 1
    1 2  4  8 16  32  64 128  256  512 1024 2048  4096 2048 1024  512  256 128  64  32 16  8  4 2 1
  1 2 4  8 16 32  64 128 256  512 1024 2048 4096  8192 4096 2048 1024  512 256 128  64 32 16  8 4 2 1
1 2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 16384 8192 4096 2048 1024 512 256 128 64 32 16 8 4 2 1

Edit: Following is a slightly longer version of the program, with intermediate variables and two functions introduced to improve readability.

def pyramid(n):
    def fieldsize(m):
        return 1+len(str(m))
    def numbers(m):
        return [2**min(j, 2*m-j) for j in range(1+2*m)]
    widths = [fieldsize(x) for x in numbers(n-1)]
    for i in range(n):
        wides = [sum(widths[:n-i])] + widths[n-i:]
        for v, w in zip(numbers(i), wides):
            print '{:{}}'.format(v, w-1),
        print

for i in range(21):
    pyramid(i)
于 2012-12-05T06:18:44.623 回答
0

错误是,您需要为每个循环清除字符串“num”,并为字符串注入清除错误的结束位置

并建议使用 list for string concact

a = [1, 2, 4, 2, 1]
s = ' '.join([str(x) for x in a])  
于 2012-12-05T03:02:34.250 回答