-1

How do I code a RADIX SORT in Python for different length of string with space?

For example my input is

["THE LORD","HELP", "WHO IS THAT"]

I would like to get

["HELP", "THE LORD", "WHO IS THAT"] 

Thank you

xQc
  • 13
  • 1
  • 5
  • 3
    Possible duplicate of [How to sort a list of words by length](https://stackoverflow.com/questions/43198074/how-to-sort-a-list-of-words-by-length) – 0x01 Mar 15 '18 at 13:29
  • 1
    This question is unclear. You want an implementation of the Radix sort algorithm to sort your list? –  Mar 15 '18 at 13:35
  • @SembeiNorimaki Yes, I want to use radix sort algorithm to sort my list – xQc Mar 15 '18 at 21:44
  • In the [Wikipedia](https://en.wikipedia.org/wiki/Radix_sort) you have an implementation of the radix algorithm in python. But do you need this algorithm for any specific reason? –  Mar 16 '18 at 13:34

2 Answers2

0

How about something like

ll=["THE LORD","HELP", "WHO IS THAT"]
sorted(ll, key=len)

Read about sorted() here.

And if you need this sorted as well, do

l=sorted(ll, key=len)
l.sort()

or using a lambda function,

l=sorted(ll, key = lambda x: (len, x))

where first the length will be considered and then the string itself.

Or if you don't want to keep the original list,

ll.sort(key=lambda x: (len, x))

sort() modifies the original list whereas sorted() makes a new one.

J...S
  • 5,079
  • 1
  • 20
  • 35
0

Wikipedia has an implementation of the Radix sorting algorithm

def radix_sort(array, base=10):
    def list_to_buckets(array, base, iteration):
        buckets = [[] for _ in range(base)]
        for number in array:
            # Isolate the base-digit from the number
            digit = (number // (base ** iteration)) % base
            # Drop the number into the correct bucket
            buckets[digit].append(number)
        return buckets

    def buckets_to_list(buckets):
        numbers = []
        for bucket in buckets:
            # append the numbers in a bucket
            # sequentially to the returned array
            for number in bucket:
                numbers.append(number)
        return numbers

    maxval = max(array)

    it = 0
    # Iterate, sorting the array by each base-digit
    while base ** it <= maxval:
        array = buckets_to_list(list_to_buckets(array, base, it))
        it += 1

    return array