Properly formatted multiplication table

前端 未结 7 2223
时光取名叫无心
时光取名叫无心 2021-02-15 11:11

How would I make a multiplication table that\'s organized into a neat table? My current code is:

n=int(input(\'Please enter a positive integer between 1 and 15:          


        
7条回答
  •  无人共我
    2021-02-15 11:23

    Gnibbler's approach is quite elegant. I went for the approach of constructing a list of list of integers first, using the range function and taking advantage of the step argument.

    for n = 12

    import pprint
    n = 12
    m = list(list(range(1*i,(n+1)*i, i)) for i in range(1,n+1))
    pprint.pprint(m)
    [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
     [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24],
     [3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36],
     [4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48],
     [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60],
     [6, 12, 18, 24, 30, 36, 42, 48, 54, 60, 66, 72],
     [7, 14, 21, 28, 35, 42, 49, 56, 63, 70, 77, 84],
     [8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 96],
     [9, 18, 27, 36, 45, 54, 63, 72, 81, 90, 99, 108],
     [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120],
     [11, 22, 33, 44, 55, 66, 77, 88, 99, 110, 121, 132],
     [12, 24, 36, 48, 60, 72, 84, 96, 108, 120, 132, 144]]
    

    Now that we have a list of list of integers that is in the form that we want, we should convert them into strings that are right justified with a width of one larger than the largest integer in the list of lists (the last integer), using the default argument of ' ' for the fillchar.

    max_width = len(str(m[-1][-1])) + 1
    for i in m:
        i = [str(j).rjust(max_width) for j in i]
        print(''.join(i))
    
       1   2   3   4   5   6   7   8   9  10  11  12
       2   4   6   8  10  12  14  16  18  20  22  24
       3   6   9  12  15  18  21  24  27  30  33  36
       4   8  12  16  20  24  28  32  36  40  44  48
       5  10  15  20  25  30  35  40  45  50  55  60
       6  12  18  24  30  36  42  48  54  60  66  72
       7  14  21  28  35  42  49  56  63  70  77  84
       8  16  24  32  40  48  56  64  72  80  88  96
       9  18  27  36  45  54  63  72  81  90  99 108
      10  20  30  40  50  60  70  80  90 100 110 120
      11  22  33  44  55  66  77  88  99 110 121 132
      12  24  36  48  60  72  84  96 108 120 132 144
    

    and demonstrate the elasticity of the spacing with a different size, e.g. n = 9

    n=9
    m = list(list(range(1*i,(n+1)*i, i)) for i in range(1,n+1))
    for i in m:
        i = [str(j).rjust(len(str(m[-1][-1]))+1) for j in i]
        print(''.join(i))
    
      1  2  3  4  5  6  7  8  9
      2  4  6  8 10 12 14 16 18
      3  6  9 12 15 18 21 24 27
      4  8 12 16 20 24 28 32 36
      5 10 15 20 25 30 35 40 45
      6 12 18 24 30 36 42 48 54
      7 14 21 28 35 42 49 56 63
      8 16 24 32 40 48 56 64 72
      9 18 27 36 45 54 63 72 81
    

提交回复
热议问题