Python 一个关于 99 乘法表的面试题目。要求将 99 乘法表存放到一个变量中,并要求通过一个 test。

2018-03-11 00:21:03 +08:00
 SuperZC
99 乘法表我能够打印出来,但不知道如何保存到一个变量中。尝试过字符串拼接,但是没成。
99 乘法表:
1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
6 12 18 24 30 36
7 14 21 28 35 42 49
8 16 24 32 40 48 56 64
9 18 27 36 45 54 63 72 81

需要通过测试函数如下:
def test_double_nine_left(self):
result = '1\n2 4\n3 6 9\n4 8 12 16\n5 10 15 20 25\n6 12 18 24 30 36\n7 14 21 28 35 42 49\n8 16 24 32 40 48 56 64\n9 18 27 36 45 54 63 72 81\n'
self.assertEqual(double_nine(right=False), result)
最后附上链接,希望能够得到帮助: https://github.com/Super1ZC/SegmentFault
2209 次点击
所在节点    Python
2 条回复
ryd994
2018-03-11 02:49:09 +08:00
"\n".join([
" ".join([
str(i*j) for j in range(1, i+1)
]) for i in range(1,10)
])
xpresslink
2018-03-11 13:20:52 +08:00
Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:57:36) [MSC v.1900 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> from itertools import groupby as gb, combinations_with_replacement as cwr
>>> from operator import mul, itemgetter as ig
>>> double_nine=lambda right: '\n'.join(map(lambda x: (lambda l: l.ljust(26) if right else l.rjust(26))(' '.join(map(lambda t: str(mul(*t)).rjust(2), ig(1)(x)))), (lambda r: gb(sorted(cwr(range(1,10),2), key=r), r))(ig(right))))
>>>
>>> print(double_nine(right=True))
1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
6 12 18 24 30 36
7 14 21 28 35 42 49
8 16 24 32 40 48 56 64
9 18 27 36 45 54 63 72 81
>>> print(double_nine(right=False))
1 2 3 4 5 6 7 8 9
4 6 8 10 12 14 16 18
9 12 15 18 21 24 27
16 20 24 28 32 36
25 30 35 40 45
36 42 48 54
49 56 63
64 72
81
>>>

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/436877

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX