如何在数字列表中找到“错误”

时间:2017-08-16 12:56:27

标签: python algorithm list recursion

对于我正在处理的项目,我必须在数字列表中找到错误。当元素出现在具有不同值的元素之后时,该元素是错误。

# Errors are indicated by a ^
l1 = [0,0,0,0,2,1,1,1,0,1,1,1,1,0,0,0]
                      ^
l2 = [2,2,1,1,1,0,0,0,0,1,0,0,3,3,2,3]
                        ^         ^

请注意l1中的最后一个零不是错误,因为我们假设列表像圆圈一样,它们位于第一个零旁边。

我尝试使用递归函数来执行此操作,但它似乎不起作用。

def Checkinter(testlist1):

    testlist = list(testlist1)
    print(len(testlist))

    if len(testlist) > 2:
        if testlist[0] not in boundaries:
            boundaries.append(testlist[0])
        if testlist[0] != boundaries[-1]:
            print('error')
        if len(testlist) == 3 and (testlist[0] == testlist[1] == testlist[2]):
            return None
        if testlist[0] == testlist[-1] and len(testlist) > 3:     
            del testlist[-1]
            Checkinter(testlist)
        if testlist[0] != testlist[-1]:
            del testlist[0]
            print(testlist)

        Checkinter(testlist)

你知道一种有效的方法吗?谢谢。

1 个答案:

答案 0 :(得分:1)

def get_errors_index(lst):
  # Delete the right element equals to left so we avoid reporting errors
  # due to cyclic values
  while lst and lst[-1] == lst[0]:
    lst.pop()
  if not lst:
    return []

  # We need to keep track of 2 indexes:
  #  - the real index, which is the index of the element in the initial
  #    iterator, used to report the erroneous indexes
  #  - the last correct index, that assumes the error did not exist
  last_indexes, errors = {}, []
  correct_index = 0

  for real_index, value in enumerate(lst):
    last_seen_index = last_indexes.get(value)
    if last_seen_index is not None and last_seen_index != correct_index:
      errors.append(real_index)
    else:
      correct_index += 1
      last_indexes[value] = correct_index

  return errors


print get_errors_index([0,0,0,0,2,1,1,1,2,1,1,1,1,0,0,0])  # [8]
print get_errors_index([0,0,0,0,2,1,1,1,0,1,1,1,1,0,0,0])  # [8]
print get_errors_index([0,0,0,0,2,1,1,1,1,1,1,1,0,0,0])  # []
print get_errors_index([0,0,0,0,2,1,1,1,1,1,1,1])  # []
print get_errors_index([0,0,0,0,2,1,2,1,1,2,1,1])  # [6, 9]
print get_errors_index([0,0,0,0,2,1,2,1,1,2,1,1,0,0])  # [6, 9]
print get_errors_index([0,0,0,0,0,0])  # []