How to see if the list contains consecutive numbers

后端 未结 12 1368
别跟我提以往
别跟我提以往 2021-02-07 12:50

I want to test if a list contains consecutive integers and no repetition of numbers. For example, if I have

l = [1, 3, 5, 2, 4, 6]

It should re

12条回答
  •  无人及你
    2021-02-07 13:29

    Here is a really short easy solution without having to use any imports:

    range = range(10)
    L = [1,3,5,2,4,6]
    L = sorted(L, key = lambda L:L)
    range[(L[0]):(len(L)+L[0])] == L
    
    >>True
    

    This works for numerical lists of any length and detects duplicates. Basically, you are creating a range your list could potentially be in, editing that range to match your list's criteria (length, starting value) and making a snapshot comparison. I came up with this for a card game I am coding where I need to detect straights/runs in a hand and it seems to work pretty well.

提交回复
热议问题