Python按字符串长度排序函数开发求助:桶排序第三步实现困境
搞定按字符串长度排序的桶排序函数
Hey there! Let's work through this bucket sort problem step by step—you're already halfway there, let's fix those tricky parts.
先修正你现有代码里的小问题
1. 计算最大长度L的逻辑错误
你当前的循环只会把最后一个单词的长度赋值给L,根本没找到真正的最大长度。正确的做法是先初始化L为0,再逐个比对更新:
# 修正后的Step 1 L = 0 for word in words: current_len = len(word) if current_len > L: L = current_len
2. 第三步:按长度分配单词到桶里
你不需要硬编码长度限制,只需要遍历每个单词,计算它的长度,然后放到对应索引的桶里就行。注意你注释里的规则:长度为1的单词放buckets[0],长度为2的放buckets[1],所以桶的索引是单词长度 - 1。代码如下:
# 修正后的Step 3 for word in words: word_len = len(word) buckets[word_len - 1].append(word)
完整修正后的代码
把这些修改整合后,完整的函数就可以正常工作了:
def empty_buckets(n): """Return a list with n empty lists. Assume n is a positive integer. """ buckets = [] for bucket in range(n): buckets.append([]) return buckets def bucket_sorted(words): """Return a new list with the same words, but by increasing length. Assume words is a non-empty list of non-empty strings. """ # Step 1. Compute the maximum length L of all words. L = 0 for word in words: current_len = len(word) if current_len > L: L = current_len # Step 2. Create a list of L empty lists (buckets). buckets = empty_buckets(L) # Step 3. Put each word in the bucket corresponding to its length for word in words: word_len = len(word) buckets[word_len - 1].append(word) # Step 4. Put all buckets together into a single list of words. newList = [] for bucket in buckets: newList.extend(bucket) # 用extend比+拼接列表更高效 return newList
测试验证
用你给出的示例输入测试一下:
print(bucket_sorted(['my', 'name', 'is', 'John'])) # 输出结果:['my', 'is', 'name', 'John']
长度相同的单词会保持原输入的顺序,这是桶排序的稳定特性哦。
内容的提问来源于stack exchange,提问作者user11125584
相关产品推荐
相关产品推荐

