编辑数字的距离指定实现。python

2024-10-01 07:35:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我在code chef上遇到了一个问题,询问编辑距离的修改版本,其中是两个数字之间的编辑距离,其中只允许删除操作,删除成本=删除的数字

所以我尝试在python上实现它。但是

TypeError: 'function' object has no attribute '__getitem__' 

我在最后一行(即EditDisRec函数中的返回行)中遇到此错误

这是密码

def ISTHERE(x,y):
    a=len(str(y))
    b=y
    for i in range(0,a):
        if b%10 == x:
            return(True)
            break
        else:
            b=b/10
    return(False)            


def sum_digits(N):
    n=int(N)
    s = 0
    while n:
        s += n % 10
        n //= 10
    return s
def delt(x,y):
    if int(x)==int(y):
        return 0
    else:
        return int(x)+int(y)

def EditDistRec(S,T):
    if S==0:
        return sum_digits(T)
    elif T==0:
        return sum_digits(S)
    elif (S==1 or S==2 or S==3 or S==4 or S==5 or S==6 or S==7 or S==8 or S==9 ):
        if ISTHERE(S,T)==True :
            return sum_digits(T) - S 
        elif ISTHERE(S,T)==False:
            return sum_digits(T)
    elif (T==1 or T==2 or T==3 or T==4 or T==5 or T==6 or T==7 or T==8 or T==9 ):
        if ISTHERE(T,S)==True :
            return sum_digits(S) - T 
        elif ISTHERE(T,S)==False:
            return sum_digits(S) 


    return min(EditDistRec(S/10,T/10) + delt[S%10,T%10],(EditDistRec(S ,T/10) + int(T%10)),(EditDistRec(S/10,T ) + int(S%10)))


print(EditDistRec(7315,713))

Tags: orfalsetrue编辑距离returnifdef
1条回答
网友
1楼 · 发布于 2024-10-01 07:35:16

您在这里输入了错别字delt[S%10,T%10]

这意味着您不能像列表一样对它们进行索引,因为getitem是处理此操作的方法。delt是一个函数,而不是列表

更正:

return min(EditDistRec(S/10,T/10) + delt(S%10,T%10),(EditDistRec(S ,T/10) + int(T%10)),(EditDistRec(S/10,T ) + int(S%10)))

输出:

sh-4.3$ python main.py                                                             
7
sh-4.3$

相关问题 更多 >