Home > database >  Using short representation in list with values where remainder is 1
Using short representation in list with values where remainder is 1

Time:11-13

I am trying to find every value in the list which has a remainder of 1 by comparing the current value to the next one and output them in a short representation.

For example a list of [1,2,3,4,5,10, 20, 30] should be outputted as 1-5 10 20 30, where every current value to the next one has a remainder of 1, and leave the rest of the list as it is.

numbers = [2,3,4,5,6, 12, 13, 14, 120, 125]
sorted_number = sorted(numbers)
# 1 2 3 120 140 141 142
shortest_sep = {}
not_shortest = []

for index in range(0, len(sorted_number)):
    if index < len(sorted_number) - 1:
        current = sorted_number[index]
        next = sorted_number[index   1]
        prev = sorted_number[index - 1]

        if (next % current) == 1:
            print(current, ":", next)
            
print(not_shortest)

CodePudding user response:

This might be a little overcomplicated (there's invariably a better way) but it does seem to work and handle other edge cases I've tested.

alist = [1, 2, 3, 4, 5, 10, 20, 30]

def func(a):
    result = [str(a[0])]
    m = False
    for prev, n in zip(a, a[1:]):
        if n - prev == 1:
            m = True
        else:
            if m:
                result[-1]  = f'-{prev}'
                m = False
            result.append(str(n))
    if m:
        result[-1]  = f'-{a[-1]}'
    return result

print(*func(alist))

Output:

1-5 10 20 30
  • Related