在Python中计算字符串长度时出现“递归深度超出错误”

时间:2019-04-20 11:14:26

标签: python algorithm

我正在尝试实现python 2.7中本课程中提到的Karatsuba算法。这是我目前获得的代码:

# Karatsuba multiplication implementation in python

import numpy as np
import sys

# x = 10^(n/2)*a + b and y = 10^(n/2)*c + d
# x.y = 10^n*(ac) + 10^(n/2)*(ad + bc) + bd
# now recursively compute ac, ad, bc and bd

sys.setrecursionlimit(15000)

def algo_recurs(val1, val2):
  # Assuming that the length of both the multiplier and multiplicand is 
    same
  # Currently employing numbers which are of length 2^n
  n = len(str(val1))            # n = 4
  print(n)
  divVal    = 10**(n/2)
  a = val1 / divVal         # a = 12
  b = val1 % divVal         # b = 34
  c = val2 / divVal         # c = 43
  d = val2 % divVal         # d = 21
  # let the example case be 1234 * 4321

  if(len(str(val1)) == 2):
    prob1 = a * c
    prob2 = b * d
    prob3 = (a+b)*(c+d) - prob1 - prob2
    finalResult = prob1*(divVal*divVal)+prob3*divVal+prob2
    return(finalResult)
  else:
    prob1 = algo_recurs(a,c)
    prob2 = algo_recurs(b,d)
    prob3 = algo_recurs((a+b),(c+d)) - prob1 -prob2
    finalResult = prob1*(divVal*divVal)+prob3*divVal+prob2
    #print(finalResult)
    return(finalResult)
#Enter the inputs

multiplicand    = input("Enter the multiplicand:")
multiplier      = input("Enter the multiplier:")
output = algo_recurs(multiplicand, multiplier)  
print(output)

上面的代码对于长度为4或更小的数字可以很好地工作。但是,当我超出此范围时,它会引发以下错误:

File "Karatsuba.py", line 31, in algo_recurs
  prob1 = algo_recurs(a,c)
File "Karatsuba.py", line 31, in algo_recurs
  prob1 = algo_recurs(a,c)
File "Karatsuba.py", line 31, in algo_recurs
  prob1 = algo_recurs(a,c)
File "Karatsuba.py", line 15, in algo_recurs
  n = len(str(val1))            # n = 4
RuntimeError: maximum recursion depth exceeded while getting the str of an object

我也增加了递归限制,以为可能是问题所在。但这也没有解决。

如果您能指出我在实施中可能做错了什么,我将不胜感激。

2 个答案:

答案 0 :(得分:0)

无论您设置的递归限制有多高,您的算法都将永远不会终止。这是因为一旦val1达到一位数字,参数a和c就会始终保持不变,因为此时n为1,10**(n/2)也为1。

答案 1 :(得分:-1)

更改递归限制很危险,因为通常当您超过递归限制时,这是因为您的程序包含错误或较差的设计决策。递归始终可以用相等或更低的内存成本的迭代来代替。

除非您的算法坚持让您知道这样做会在某个时候收到结果,否则您每次调用函数时都可以更改最大递归深度,但是我不建议您这样做,因为您的程序已超过1500次递归调用当您将其设置为该值时,那太过分了。

{
  "foo" : {
    "a" : 1,
    "b" : 2
  },
  "bar" : {
    "a" : 1,
    "b" : 2
  }
}