How to report an error if an item is missing in se

2019-08-23 20:44发布

This question is an exact duplicate of:

for i, e in enumerate(l1):
    if (e[0] == e[1]) and ((e[0], e[1]) not in l1):
        raise ValueError, '%s is missing' %(e[0], e[1])

    if i!=len(l1)-1:
        if e[0]==l1[i+1][0] and e[1]!=l1[i+1][1]-1:
            raise ValueError, '(%s,%s) is missing ' %(e[0], e[1]+1)

l1 = [(1, 2), (1, 3), (1, 4), (2, 1), (2, 3)]

I am able to work for missing (1,2) and (2,2) but in the above case first it should look for (1,1) to report an error if it's not there however in the above code it goes undetected. Likewise it should traverse the whole list to check if any thing is missing. also what if I want (2,4) and its missing in l1. There should be a error been reported here as well

标签: python
3条回答
仙女界的扛把子
2楼-- · 2019-08-23 20:53

In general terms:

from itertools import product

#`m` and `n` denote the upper limit to the domain of the first and second tuple elements.
complete_set = set(product(range(1, n), range(1, m)))

#`i` is whichever sublist you want to test. You get the idea.
test_set = set(l1[i])

missing_set = complete_set - test_set

EDIT

To check if a sequence is out of order:

sorted(sequence) == sequence
查看更多
【Aperson】
3楼-- · 2019-08-23 20:58
l1=[(1, 1), (1, 2), (1, 4), (2, 1), (2, 2), (2, 5)]
for i,elem in enumerate(l1[:-1]):
    nxt = ((elem[0],elem[1]+1),(elem[0]+1,elem[1]))
    if l1[i+1] not in nxt:
       print "Error, something is missing should be one of:",list(nxt)

output:

Error, something is missing should be one of: [(1, 3), (2, 2)]
Error, something is missing should be one of: [(1, 5), (2, 4)]
Error, something is missing should be one of: [(2, 3), (3, 2)]
查看更多
闹够了就滚
4楼-- · 2019-08-23 21:02

I'm ignoring your other question as you would simply need to check whether the front letters are the same.

EDIT: Apparently I missed some. New solution that is horribly inefficient and kind of ugly:

missing = []
num = {}
for i,e in enumerate(l1):
    if not e[0] in num:                # first number groups
        num[e[0]] = []                 # make a list of them (empty... for now)
        for z,q in enumerate(l1):      # for all of the numbers
            if q[0]==e[0]:             # that are in the first number group
                num[e[0]].append(q[1]) # append 
                                       # then start again with second number group

for i in num.keys():                            # for each number group
    for e in xrange(min(num[i]),max(num[i])+1): # from minimum to maximum, iterate
        if not e in num[i]:                     # if any number isn't there
            missing.append((i,e))               # make note

print missing # [(1, 3), (2, 3), (2, 4), (3, 2)]
查看更多
登录 后发表回答