如何在不使用嵌套循环的情况下显示乘法表?

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

是否可以在不使用嵌套循环的情况下显示这个乘法表?


如果是,怎么办?


我的意思是,我只想使用一个循环。


慕森卡
浏览 90回答 3
3回答

茅侃侃

你可以循环100次,然后用除法和模数来确定你当前的行和列,然后计算相应的乘积。for i in range(0, 100):    row = 1 + i // 10    col = 1 + i % 10    print(row * col, end="\t")    if col == 10:        print()

冉冉说

您可以在没有任何显式循环甚至关键字的情况下执行此操作for。>>> from operator import mul>>> from functools import partial>>>&nbsp;>>> print("\n".join(map(lambda n: "".join(map("{:<3}".format, map(partial(mul, n), range(1,11)))), range(1,11))))1&nbsp; 2&nbsp; 3&nbsp; 4&nbsp; 5&nbsp; 6&nbsp; 7&nbsp; 8&nbsp; 9&nbsp; 10&nbsp;2&nbsp; 4&nbsp; 6&nbsp; 8&nbsp; 10 12 14 16 18 20&nbsp;3&nbsp; 6&nbsp; 9&nbsp; 12 15 18 21 24 27 30&nbsp;4&nbsp; 8&nbsp; 12 16 20 24 28 32 36 40&nbsp;5&nbsp; 10 15 20 25 30 35 40 45 50&nbsp;6&nbsp; 12 18 24 30 36 42 48 54 60&nbsp;7&nbsp; 14 21 28 35 42 49 56 63 70&nbsp;8&nbsp; 16 24 32 40 48 56 64 72 80&nbsp;9&nbsp; 18 27 36 45 54 63 72 81 90&nbsp;10 20 30 40 50 60 70 80 90 100但它仍然是 O(n^2)。不管你怎么写,你都需要计算并输出 O(n^2) 的乘积。不过,最简单的解决方案是像您已经拥有的那样使用两个循环。

慕沐林林

如果其他函数可以为您执行嵌套循环,您可以使用itertools.product:>>> from itertools import product>>> for a, b in product(range(1, 11), repeat=2):...&nbsp; &nbsp; &nbsp;print(a * b, end="\t")...&nbsp; &nbsp; &nbsp;if b == 10:...&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;print()...1&nbsp; &nbsp;2&nbsp; &nbsp;3&nbsp; &nbsp;4&nbsp; &nbsp;5&nbsp; &nbsp;6&nbsp; &nbsp;7&nbsp; &nbsp;8&nbsp; &nbsp;9&nbsp; &nbsp;102&nbsp; &nbsp;4&nbsp; &nbsp;6&nbsp; &nbsp;8&nbsp; &nbsp;10&nbsp; 12&nbsp; 14&nbsp; 16&nbsp; 18&nbsp; 203&nbsp; &nbsp;6&nbsp; &nbsp;9&nbsp; &nbsp;12&nbsp; 15&nbsp; 18&nbsp; 21&nbsp; 24&nbsp; 27&nbsp; 304&nbsp; &nbsp;8&nbsp; &nbsp;12&nbsp; 16&nbsp; 20&nbsp; 24&nbsp; 28&nbsp; 32&nbsp; 36&nbsp; 405&nbsp; &nbsp;10&nbsp; 15&nbsp; 20&nbsp; 25&nbsp; 30&nbsp; 35&nbsp; 40&nbsp; 45&nbsp; 506&nbsp; &nbsp;12&nbsp; 18&nbsp; 24&nbsp; 30&nbsp; 36&nbsp; 42&nbsp; 48&nbsp; 54&nbsp; 607&nbsp; &nbsp;14&nbsp; 21&nbsp; 28&nbsp; 35&nbsp; 42&nbsp; 49&nbsp; 56&nbsp; 63&nbsp; 708&nbsp; &nbsp;16&nbsp; 24&nbsp; 32&nbsp; 40&nbsp; 48&nbsp; 56&nbsp; 64&nbsp; 72&nbsp; 809&nbsp; &nbsp;18&nbsp; 27&nbsp; 36&nbsp; 45&nbsp; 54&nbsp; 63&nbsp; 72&nbsp; 81&nbsp; 9010&nbsp; 20&nbsp; 30&nbsp; 40&nbsp; 50&nbsp; 60&nbsp; 70&nbsp; 80&nbsp; 90&nbsp; 100
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python