为什么我没有得到某些值的输出

时间:2019-09-15 05:51:51

标签: python karatsuba

以下是python中的代码,我尝试实现了递归的Karatsuba算法。我没有为输入1234、5678输入正确的值。另外,对于值55,15,我得到了错误消息。我迷迷糊糊了几个小时,请您帮忙。 谢谢

x = input("Enter a number: ")
y = input("Enter another number: ")



def ksml (p,q):
    p = str(p)
    q = str (q)
    n = len(p)
    # mid is to be made int because when used to strip num, range has to be in num not float
    mid = int(n/2)
    if n == 1:
        p = int(p)
        q = int(q)
        product = p * q
        return product
    else:
        a = int(p[0:mid])
        b = int(p[mid:])
        c = int(q[0:mid])
        d = int(q[mid:])
        # parts of the prodcut
        k = ksml(a,c)
        l = ksml (b,d)
        m = ksml (a+b,c+d) - k - l
        product = (10 ** n * k) + (10 ** mid * m) + l
        return product

print(ksml(x,y))

我得到的错误是

Enter a number: 55
Enter another number: 15
Traceback (most recent call last):
  File "test1.py", line 27, in <module>
    print(ksml(x,y))
  File "test1.py", line 23, in ksml
    m = ksml (a+b,c+d) - k - l
  File "test1.py", line 19, in ksml
    d = int(q[mid:])
ValueError: invalid literal for int() with base 10: ''

1 个答案:

答案 0 :(得分:0)

您的问题在这里:mid = int(n/2)因为您要转换为int,所以结果可能为零。您可能应该四舍五入,但是我对算法的了解还不够确定。

考虑使用数字位数p会发生什么。 n=len(p)现在为0.5,mid=int(n/2)现在为零,并且p[0:mid]实际上只是一个空字符串。尝试将空字符串放入int会导致出现错误。

如果我是正确的,那么您应该四舍五入(这样一来您至少会得到1的值),则应该使用math.ceil

import math
mid = math.ceil(n) # will be 1 if n was 0.5