Home > Blockchain >  Python: Alternate sorting of chunks in a list
Python: Alternate sorting of chunks in a list

Time:07-20

Create a list (*for example, the size of 40 items) and fill it with random items.

Sort the list by 10 elements. That is, sort the first 10 elements in ascending order, the second ten elements in descending order, the third ten elements in ascending order, and the fourth in descending order.

The answer must be returned in one list!!!

*example - meaning that this is an approximate version of the size of the list, and you need to write an algorithm that can sort a list of any size.

from random import randint

list_1 = [randint(1, 100) for i in range(30)]


first_part = list_1[:10]
first_part.sort()
second_part = list_1[10:20]
second_part.sort(reverse=True)
third_part = list_1[20:30]
third_part.sort()

print(first_part second_part third_part)

I dont understand how to write an algorithm that can sort a list of any size.

CodePudding user response:

One method by which this can be accomplished is by iterating the list of data in (n) size chunks, then calling the sorted function with the reverse parameter with either a value of 0 or 1, which is derived by the odd/even value of the iteration.

For example:

import random

data = [random.randint(1, 100) for _ in range(30)]

out = []
for idx, chunk in enumerate(range(0, len(data), 10)):
    out.extend(sorted(data[chunk:chunk 10], reverse=idx%2))

Output:

[6, 10, 16, 24, 26, 50, 57, 72, 94, 94,   # asc
 88, 82, 59, 44, 25, 22, 20, 19, 14, 9,   # desc
 16, 18, 29, 37, 45, 45, 76, 84, 93, 93]  # asc

CodePudding user response:

You could sort the whole list with one call to sorted with a key callback that produces a tuple with the following members:

  • the "bucket": the sequence number of the sublist to sort, i.e. the index of the element divided by 10
  • the value to be sorted in ascending order within that bucket, i.e. either the value itself (for even buckets), or its negated value (for odd buckets)

Implementation:

def order(pair):
    i, val = pair
    bucket = i // 10
    return bucket, -val if bucket % 2 else val

lst = [randint(1, 100) for i in range(30)]

result = [val for _, val in sorted(enumerate(lst), key=order)]

CodePudding user response:

You can try something like this :-

from random import randint

list_1 = [randint(1, 100) for i in range(30)]
print(list_1)

final_list = []

for i in range(0, len(list_1), 10):
    buf = list_1[i:i 10]
    buf.sort()
    for each in buf : final_list.append(each)

print(final_list)
  • Related