def fast_mul(a, b, s, d):
if b == 1:
print(s,a,') '*d)
return a
else:
if even(b):
print(s+f'2 * fast_mul({a}, {b//2})',') '*d)
return 2 * fast_mul(a, b//2, s+'2 * ( ',d+1)
if odd(b):
print(s+f'{a} + 2 * fast_mul({a}, {b//2})', ') '*d)
return a + 2 * fast_mul(a, b//2,s+f'{a} + 2 * ( ',d+1)
def even(n):
return n % 2 == 0
def odd(n):
return n % 2 == 1
print(fast_mul(3, 7,'',0))
I added two more parameters in the function, s and d.
(我在函数s和d中添加了两个参数。)
s stores the string that's carried over from the previous recursion call
(s存储从上一个递归调用中继承的字符串)
d stores the depth of recursion so we can figure out how many closing brackets to add to the string.
(d存储递归的深度,因此我们可以算出要在字符串中添加多少个右括号。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…