I have implemented a radix sort algorithm in Python 3. It first finds the maximum number of digits in the list, then changes them to strings and adds 0's. For example, [7, 23, 107, 1, 53] to ['007', '023', '107', '001', '053']. I then make a new matrix, [[] * 10]. I append the numbers with last digit of 0 in lst[0], numbers with last digit of 1 in lst[1], etc. I then flatten the matrix into a list, and recurse with the lst, and with the position one less than the one before (in this case, the second to last digit). Can I get advice on how to improve it? Here is my code:
def radix_sort(lst):
'''list -> list'''
#finds maximum number of digits in list
num_of_digits = max([len(str(x)) for x in lst])
#Adds 0s to the front of the number if necessary and changes it to a string
for x in range(len(lst)):
lst[x] = '0' * (num_of_digits - len(str(lst[x]))) + str(lst[x])
#helper function to sort based on the position
def helper(lst, pos):
'''list, int -> list'''
#places numbers with 0 in the position in the ans[0], 1 in the position in ans[1], etc.
ans = [[] for _ in range(10)]
#adding numbers to the position in ans
for x in lst:
ans[int(x[pos])].append(x)
#flattened list, reusing lst to save memory
lst = []
for x in ans:
for y in x:
lst.append(y)
#we have sorted the whole list
if pos == 0:
return lst
#recurse again with smaller position
return helper(lst, pos - 1)
#changing the strings to integers and returning
return [int(x) for x in helper(lst, num_of_digits - 1)]