簡體   English   中英

如何在不使用嵌套循環的情況下顯示乘法表?

[英]How can I display a multiplication table without using nested loops?

for i in range(1,11,1):
  for j in range(1,11,1):
    print(i*j, end="\t")
  print()

輸出

1   2   3   4   5   6   7   8   9   10
2   4   6   8   10  12  14  16  18  20
3   6   9   12  15  18  21  24  27  30
4   8   12  16  20  24  28  32  36  40
5   10  15  20  25  30  35  40  45  50
6   12  18  24  30  36  42  48  54  60
7   14  21  28  35  42  49  56  63  70
8   16  24  32  40  48  56  64  72  80
9   18  27  36  45  54  63  72  81  90
10  20  30  40  50  60  70  80  90  100

是否可以在不使用嵌套循環的情況下顯示此乘法表?

如果是,如何?

我的意思是,我只想使用一個循環。

你可以循環100次,然后用除法和取模來確定你當前的行和列,然后計算出合適的乘積。

for i in range(0, 100):
    row = 1 + i // 10
    col = 1 + i % 10
    print(row * col, end="\t")
    if col == 10:
        print()

如果其他函數可以為您執行嵌套循環,則可以使用itertools.product

>>> from itertools import product
>>> for a, b in product(range(1, 11), repeat=2):
...     print(a * b, end="\t")
...     if b == 10:
...         print()
...
1   2   3   4   5   6   7   8   9   10
2   4   6   8   10  12  14  16  18  20
3   6   9   12  15  18  21  24  27  30
4   8   12  16  20  24  28  32  36  40
5   10  15  20  25  30  35  40  45  50
6   12  18  24  30  36  42  48  54  60
7   14  21  28  35  42  49  56  63  70
8   16  24  32  40  48  56  64  72  80
9   18  27  36  45  54  63  72  81  90
10  20  30  40  50  60  70  80  90  100

您可以在沒有任何顯式循環甚至關鍵字for情況下執行此操作。

>>> from operator import mul
>>> from functools import partial
>>> 
>>> print("\n".join(map(lambda n: "".join(map("{:<3}".format, map(partial(mul, n), range(1,11)))), range(1,11))))
1  2  3  4  5  6  7  8  9  10 
2  4  6  8  10 12 14 16 18 20 
3  6  9  12 15 18 21 24 27 30 
4  8  12 16 20 24 28 32 36 40 
5  10 15 20 25 30 35 40 45 50 
6  12 18 24 30 36 42 48 54 60 
7  14 21 28 35 42 49 56 63 70 
8  16 24 32 40 48 56 64 72 80 
9  18 27 36 45 54 63 72 81 90 
10 20 30 40 50 60 70 80 90 100

不過,它仍然是 O(n^2)。 不管你怎么寫這個,你都需要計算和輸出 O(n^2) 個乘積。

不過,最簡單的解決方案是使用您已有的兩個循環。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM