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