从合法编号的模式中删除闯入者

时间:2012-07-06 19:23:09

标签: python algorithm pattern-matching

我有一个遵循legal numbering计划

的数字列表

列表如下所示 -

['1', '1', '1.1', '1.2', '1.3', '1.4', '1.5', '2', '1.6', '2', '2.1', '2.2', '2.3', '2.4', '3', '2.5', '3', '3.1', '3.2', '4', '5', '4', '6', '6.1', '6.2', '9333', '6.3', '6.4', '5', '6.5', '6.6', '6.7', '6.8', '6.9', '6.10', '6', '7']

此列表中有 '整数' 闯入者(与方案不一致的数字)。例如,列表顶部的第一个'1','1.6'之前的'2'。是否有已知的算法或模式来识别不一致的数字并将其从列表中删除?

编辑:由于某些人不清楚这个问题,我已经发布了一个合法编号的方案:

['1','1.1','1.2','1.3','2','2.1','3','3.1','3.2'....]

但请注意,我无法将其与静态列表进行比较,因为这只是一种编号方案。 “2”之后可以是“2.1”,然后是“3”,或者可以是“2.1”,“2.2”,然后是“3”。

3 个答案:

答案 0 :(得分:4)

for a,b in zip(mylist, mylist[1:]):
    if a==b:
        print('Value {} is repeated'.format(a))
    elif a > b:
        print('Either {} or {} is out of order'.format(a,b))

在您的数据上,这会给出

Value 1 is repeated
Either 2 or 1.6 is out of order
Either 3 or 2.5 is out of order
Either 5 or 4 is out of order
Either 9333 or 6.3 is out of order
Either 6.4 or 5 is out of order
Either 6.9 or 6.10 is out of order
Either 6.10 or 6 is out of order

可选地,

mylist = sorted(set(mylist))

自动删除重复项并将所有内容整理好。

编辑:Mark Byers提出了一个关于6.9 / 6.10没有正确排序的好点;我看到的唯一解决方案是解析字符串,以便我们比较整数,如下所示:

mylist = sorted(set(mylist), key=lambda s:map(int, s.split('.')))

结果

['1', '1.1', '1.2', '1.3', '1.4', '1.5', '1.6', '2', '2.1', '2.2', '2.3', '2.4', '2.5', '3', '3.1', '3.2', '4', '5', '6', '6.1', '6.2', '6.3', '6.4', '6.5', '6.6', '6.7', '6.8', '6.9', '6.10', '7', '9333']

答案 1 :(得分:2)

您基本上希望将其与列表的排序版本进行比较

for a, b in zip(numbers, sorted(numbers, key=lambda x: x.split('.'))):
    if a != b:
       print('error at ' + a)
       # or do something else

答案 2 :(得分:1)

试试这个:

def get_next_dotted_term(s, i):
    for x in s[i + 1:]:
        if '.' in x:
            return int(x.partition('.')[0])

def make_valid(s):
    result = []
    current = 0

    for i, x in enumerate(s):
        if '.' in x:
            result.append(x)
        else:
            ix = int(x)
            nextdot = get_next_dotted_term(s, i)
            if current + 1 == ix and (ix <= nextdot or not nextdot):
                result.append(x)
                current += 1
            else:
                print "Error: " + x
    return result

print make_valid(['1','1.1','2','1.2','2','3','3.1','3.2','4','3.3','3.4'])

结果:

Error: 2
Error: 4
['1', '1.1', '1.2', '2', '3', '3.1', '3.2', '3.3', '3.4']