2016-10-17 66 views
2

我有一個只包含整數的列表,我想檢查列表中的所有數字是否連續(數字的順序無關緊要)。測試列表中的連續數字

如果有重複的元素,該函數應該返回False。

這是我試圖解決這個問題:

def isconsecutive(lst): 
    """ 
    Returns True if all numbers in lst can be ordered consecutively, and False otherwise 
    """ 
    if len(set(lst)) == len(lst) and max(lst) - min(lst) == len(lst) - 1: 
     return True 
    else: 
     return False 

例如:

l = [-2,-3,-1,0,1,3,2,5,4] 

print(isconsecutive(l)) 

True 

這是做到這一點的最好方法是什麼?

+0

您的示例列表不是連續的 - 它可以重新排序爲連續的整數,是什麼意思?我們可以重新排列名單嗎? –

+1

@DanielleM。順序沒關係 – MMF

+0

看起來很好,但你應該刪除if並只是返回整個表達式 –

回答

4

這裏是另一種解決方案:

def is_consecutive(l): 
    setl = set(l) 
    return len(l) == len(setl) and setl == set(range(min(l), max(l)+1)) 

然而,您的解決方案可能是更好,因爲你不存儲在內存中的整個範圍。

請注意,您可以隨時通過

return boolean_expression 
+0

不錯的Julien;) – MMF

+0

我會補充一點,只要'test'是一個布爾值,'return test'是相等的,否則你將不得不打電話給'bool' –

+0

@FranciscoCouzo,這是真的,我只是做了一個編輯。 –

1

在你看多少次在元素方面更好的方法簡化

if boolean_expression: 
    return True 
else: 
    return False 

將納入找到分鐘最大短路任何重複都在一個過程中,雖然可能會被內置函數的速度擊敗ons取決於輸入:

def mn_mx(l): 
    mn, mx = float("inf"), float("-inf") 
    seen = set() 
    for ele in l: 
     # if we already saw the ele, end the function 
     if ele in seen: 
      return False, False 
     if ele < mn: 
      mn = ele 
     if ele > mx: 
      mx = ele 
     seen.add(ele) 
    return mn, mx 

def isconsecutive(lst): 
    """ 
    Returns True if all numbers in lst can be ordered consecutively, and False otherwise 
    """ 
    mn, mx = mn_mx(lst) 
    # could check either, if mn is False we found a dupe 
    if mn is False: 
     return False 
    # if we get here there are no dupes 
    return mx - mn == len(lst) - 1