Home > front end >  Find different elements individual or series in a list of non duplicate random numbers
Find different elements individual or series in a list of non duplicate random numbers

Time:03-06

I have a list of numbers, for example: [4,5,6,8,229,230,250,170,118,119,120].

I'm trying to make a function that would give:

results = [4 to 6, 8, 118 to 120, 170, 229 to 230, 250]

Thank you for the help.

CodePudding user response:

The question of how the sequences should be represented is unclear. One way would be to have the sequences as tuples within the list - i.e., just storing the first and last numbers in the sequence.

For example:

lst = [4,5,6,8,229,230,250,170,118,119,120]

lst.sort()

result = [lst[0]]

for x in lst[1:]:
    istuple = isinstance(result[-1], tuple)
    y = result[-1][-1] if istuple else result[-1]
    if x - y > 1:
        result.append(x)
    else:
        result[-1] = (result[-1][0], x) if istuple else (result[-1], x)

print(result)

Output:

[(4, 6), 8, (118, 120), 170, (229, 230), 250]
  • Related