比较两个整数的相似性

时间:2011-11-02 22:54:35

标签: python comparison similarity

示例:

number1 = 54378
number2 = 54379
if number1 (is similar to) number2:
   print (number1 + " " + number2)
   input("what to do")

我想在这两个数字之间进行比较,让程序在发生这种(在number1和number2之间)相似时通知我。

我希望解决方案具有灵活性,可以提供更多相似之处(_84第一位数字不同)。

BTW,我正在使用Python 3.X

2 个答案:

答案 0 :(得分:3)

您可以使用difflib

>>> from difflib import SequenceMatcher
>>> number1 = 54378
>>> number2 = 54379
>>> SequenceMatcher(None, str(number1), str(number2)).ratio()
0.80000000000000004

创建一个包含其数字字符串表示的SequenceMatcher对象后,如果速度有问题,请使用ratio()(或quick_ratio()real_quick_ratio()来获取相似度0和1。

在玩了一下之后,你可以弄清楚它们应该是多么相似的好指标,并像这样使用它:

metric = 0.6   # just an example value
if SequenceMatcher(None, str(a), str(b)).ratio() > metric:
    # a and b are similar

答案 1 :(得分:0)

您可以执行以下操作之一:
两者都会采用不均匀的数字,例如(100, 10) (200, 12)

from itertools import izip_longest
def findSim(a, b):
    aS = str(a)
    bS = str(b)

    return [abs(int(x)-int(y)) if y != None else int(x) for x,y in izip_longest(aS,bS)]

返回包含所有位置差异的列表

from itertools import izip_longest
def findSim(a, b):
    aS = str(a)
    bS = str(b)

    return sum(abs(int(x)-int(y)) if y != None else int(x) for x,y in izip_longest(aS,bS))

返回所有位置的总和差异。

相关问题