我有一个函数,它使用binsort(bucketsort(对包含整数的List OF LISTS进行排序,但只有当整数只有1位时,它才有效。例如,我输入数组[[1,4,2]、[6,4,2]、[1,4,1]],输出为[[1,4,1]、[11,4,2]和[6,4,2]]。
但是,当我输入一个数组时,该数组的数字为<1个数字,我得到一个";列表索引超出范围"例如,下面的数组给了我一个错误,[[22,11,1],[1,13,4]]。
我希望[[22,11,1],[1,13,4]]的输出是[[1,13,4],[22,11,1]],所以它是按顺序排序的。
我该如何修复我的函数,使其对每个数字看两次(第一次看一个位置并将其放入正确的箱子,然后第二次也是最后一次看十个位置并移动到正确的箱子(,并在看了十个位置后将其放入最后的正确箱子?
def binsort(a):
bins = [a]
for l in range(len(a[0])-1, -1, -1):
binsTwo = [[] for _ in range(10)]
for bin in bins:
for e in bin:
binsTwo[e[l]].append(e)
bins = binsTwo
return [e for bin in bins for e in bin]
很抱歉,如果这让人感到困惑,如果有任何问题,我会试着详细介绍。谢谢你的帮助。
您写道,您需要一个"对整数列表"进行排序的函数,但在您的代码中,您将列表的列表传递给binsort
。只有当这些子列表表示一个数字的数字时,这才有意义。当这些数字不再是个位数时,就没有意义了。任一:
- 您可以对像
[142, 642, 141]
这样的整数列表进行排序,或者 - 您可以对数字列表进行排序,如
[[1,4,2], [6,4,2], [1,4,1]]
,其中每个子列表都是整数的逐位数表示
混合整数的两种表示没有什么意义。
以下是使用第一种表示时的操作方法:
def binsort(a):
if not a: # Boundary case: list is empty
return a
bins = [[], a]
power = 1
while len(bins[0]) < len(a): # while there could be more digits to binsort by
binsTwo = [[] for _ in range(10)]
for bin in bins:
# Distribute the numbers in the new bins according to i-th digit (power)
for num in bin:
binsTwo[num // power % 10].append(num)
# Prepare for extracting next digit
power *= 10
bins = binsTwo
return bins[0]
如果您使用第二种表示形式(单个数字的列表列表(,那么您的代码就可以了,前提是您添加了对空输入列表的检查,这是一种边界情况。
def binsort(a):
if not a: # Boundary case: list is empty
return a
bins = [a]
for i in range(len(a[0]) - 1, -1, -1): # For each digit
binsTwo = [[] for _ in range(10)]
for bin in bins:
# Distribute the numbers in the new bins according to i-th digit
for digits in bin:
binsTwo[digits[i]].append(digits)
# Prepare for extracting next digit
bins = binsTwo
return [digits for bin in bins for digits in bin]
但同样,你不应该试图";解决";这种情况下,您有由多位数组成的子列表。重新考虑一下为什么您认为需要支持,因为您似乎混合了两种输入格式——正如我在上面解释的那样。
def bucketsort(a):
# Create empty buckets
buckets = [[] for _ in range(10)]
# Sort into buckets
for i in a:
buckets[i].append(i)
# Flatten buckets
a.clear()
for bucket in buckets:
a.extend(bucket)
return a