Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
236 views
in Technique[技术] by (71.8m points)

python - 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.

This is my attempt so far:

l = []
l_ = []
i = 0
while i <= len(a)-1:
    if a[i] < a[i+1]:
        l_= l_ + [a[i]]
    else:
        l = l_ + [a[i]]
        l_ = []
    i = i + 1

I'd appreciate any guidance or other approaches.

So, for the following list:

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

I would like to obtain:

[7,5,1,3,5,2,45,4,12,10,5,1]     
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 chunk
    else:
        chunk.append(i)      # add to chunk
output.extend(chunk[::-1])   # empty leftover chunk
print(output)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...