2017-08-16 18 views
-1

對於我正在處理的項目,我必須在數字列表中找到錯誤。元素出現在具有不同值的元素後面時出錯。如何在數字列表中找到「錯誤」

# 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) 

你知道一個有效的方法嗎?謝謝。

+3

據我所知,「一個元素出現在具有不同值的元素後面的錯誤」意味着前2個,前1個和第4個1也是錯誤。是這樣嗎? – bgse

+0

您能否提供更多示例並指定哪個元素是錯誤的? – stamaimer

+0

不,因爲我忘了提及一旦我們檢測到零的「badaries」,我們刪除它們並再次執行操作 – PythonItsLife

回答

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]) # [] 
+0

謝謝你的回覆。我現在要看看它 – PythonItsLife

+0

它似乎工作,但如果列表中有多個錯誤,那麼不能檢測到另一個 – PythonItsLife

+0

這是不正確的。 OP對錯誤數量的定義* n *等於* n = {列表x中的所有元素'i',其中'i-1'!='i'}×2 *。你的實現假設* n = {列表x中的所有元素'i',因爲你的代碼沒有考慮到一個獨特的元素* j *的事實,因爲它是'i-1'!='i'} *定義在前面和後面是一個唯一元素(即使在*'j-1' ='j + 1'!='j' *)的情況下也是如此。 –

相關問題