# Python 3.6 or later
def mul(a: str, b: str) -> str:
from functools import reduce
def plus(xs: list, ys: list) -> str:
zs = reduce(lambda p, xy: p.append(sum((p[-1],) + xy) // 10) or p, zip(xs, ys), [0])[:-1]
return ''.join(chr(ord('0') + sum(xyz) % 10) for xyz in zip(xs, ys, zs))[::-1].lstrip('0') or '0'
def add(x: str, y: str) -> str:
xs = [ord(i) - ord('0') for i in x[::-1]] + [0] * max(1, 1 + len(y) - len(x))
ys = [ord(i) - ord('0') for i in y[::-1]] + [0] * max(1, 1 + len(x) - len(y))
return plus(xs, ys)
def mmm(x: str, y: str) -> str:
xs = [ord(i) - ord('0') for i in x[::-1]] + [0]
ys = [x * (ord(y) - ord('0')) % 10 for x in xs]
zs = [0] + [x * (ord(y) - ord('0')) // 10 for x in xs][:-1]
return plus(ys, zs)
return reduce(lambda s, ia: add(s, mmm(b, ia[1]) + '0' * ia[0]) , enumerate(a[::-1]), '0')
【 在 No1 的大作中提到: 】
: 偶尔在《Coders at Work》看着,大家闲着没事可以活动下:
: 自己用算法实现两个任意长度十进制数的字符串相乘。
: 如“123412341234234123412341234123412341234”和 “9071238947891273489172347891927349812723498471289347”自己随便敲一串,要看结果对不对用bc -l命令对照下就行
--
FROM 183.192.11.*