Python 面试题:如何将 99 乘法表存入变量并通过测试?

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
Python 面试题:如何将 99 乘法表存入变量并通过测试?


3 回复
def create_multiplication_table():
    """生成99乘法表并返回字符串"""
    table = []
    for i in range(1, 10):
        row = []
        for j in range(1, i + 1):
            row.append(f"{j}×{i}={i*j}")
        table.append(" ".join(row))
    return "\n".join(table)

def test_multiplication_table(table_str):
    """测试生成的乘法表是否正确"""
    lines = table_str.strip().split('\n')
    
    # 测试行数
    assert len(lines) == 9, f"应该有9行,实际有{len(lines)}行"
    
    # 测试每行的内容
    for i, line in enumerate(lines, 1):
        items = line.split()
        assert len(items) == i, f"第{i}行应该有{i}个算式,实际有{len(items)}个"
        
        # 测试每个算式
        for j, item in enumerate(items, 1):
            expected = f"{j}×{i}={i*j}"
            assert item == expected, f"第{i}行第{j}个算式错误: 期望{expected}, 实际{item}"
    
    return True

# 使用示例
if __name__ == "__main__":
    # 生成乘法表
    multiplication_table = create_multiplication_table()
    
    # 打印查看
    print("生成的99乘法表:")
    print(multiplication_table)
    
    # 测试验证
    try:
        test_result = test_multiplication_table(multiplication_table)
        print("\n测试结果: 通过!")
    except AssertionError as e:
        print(f"\n测试失败: {e}")

这个方案的关键点:

  1. create_multiplication_table() 函数生成标准格式的99乘法表字符串
  2. test_multiplication_table() 函数验证格式和计算结果的正确性
  3. 使用嵌套循环构建三角形格式,每行算式数量等于行号
  4. 测试函数检查行数、每行算式数量和每个算式的正确性

代码直接运行就能看到结果和测试验证。


“\n”.join([
" ".join([
str(i*j) for j in range(1, i+1)
]) for i in range(1,10)
])

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
>>>

回到顶部