如何使用Python在不同长度的字符串中使用Python编写RADIX SORT?
例如我的输入是
["THE LORD","HELP", "WHO IS THAT"]
我想得到
["HELP", "THE LORD", "WHO IS THAT"]
谢谢
答案 0 :(得分:0)
像
这样的东西ll=["THE LORD","HELP", "WHO IS THAT"]
sorted(ll, key=len)
了解sorted()
here。
如果您还需要这样排序,请执行
l=sorted(ll, key=len)
l.sort()
或使用lambda function,
l=sorted(ll, key = lambda x: (len, x))
首先考虑长度,然后是字符串本身。
或者,如果您不想保留原始列表,
ll.sort(key=lambda x: (len, x))
sort()
修改了原始列表,而sorted()
创建了一个新列表。
答案 1 :(得分:0)
Wikipedia具有Radix排序算法的实现
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