Skip to content Skip to sidebar Skip to footer

Reversing Order In Incrementing Digits

I have a list of numbers, and I'm trying to do the following in a way as efficient as possible. For each consecutively incrementing chunk in the list I have to reverse its order. T

Solution 1:

Try this:

(with fixes from @Scott Boston and @myrmica)

nums = [1, 3, 5, 4, 6, 8, 9, 7, 2, 4] # sample input
chunk = []    # keep track of chunks
output = []   # output list
for i in nums:
    if chunk and i < chunk[-1]:
        output.extend(chunk[::-1]) # add reversed chunk to output
        chunk[:] = [i]       # clear chunkelse:
        chunk.append(i)      # add to chunkoutput.extend(chunk[::-1])   # empty leftover chunk
print(output)

Solution 2:

with comprehension lists :

a = [1,5,7,3,2,5,4,45,1,5,10,12]

split=[0]+[i for i inrange(1,len(a)) if a[i-1]>a[i]]+[len(a)]
#[0, 3, 4, 6, 8, 12]

chunks=[list(reversed(a[i:j])) for i,j inzip(split[:-1],split[1:])]
#[[7, 5, 1], [3], [5, 2], [45, 4], [12, 10, 5, 1]]print(sum(chunks,[]))   
#[7, 5, 1, 3, 5, 2, 45, 4, 12, 10, 5, 1]

Post a Comment for "Reversing Order In Incrementing Digits"