python程序按元音计数排序

时间:2018-07-03 18:16:19

标签: python sorting

此代码有什么问题??它显示了最后两种情况的断言错误,即[“ aunt”,“ engine”,“ aeiou”]和[“ aunt”,“ ENGINE”,“ aeiou”]

def  vowel(word):
    return len(set("aeiou")&set(word.lower()))

def sort_by_vowel_count(words):
    if(words!=None):
    words.sort(key=vowel,reverse=True)


def single_sort_by_vc_test(input, result):
    sort_by_vowel_count(input)
    assert result == input

def test_sort_by_vowel_count():
    single_sort_by_vc_test(["engine", "ant", "aeiou"], ["aeiou", "engine", "ant"])
    single_sort_by_vc_test(["engine", "ant", "aeroplane", "key", "bcdgcdbcd"], ["aeroplane", "engine", "ant", "key", "bcdgcdbcd"])
    single_sort_by_vc_test([], [])
    single_sort_by_vc_test(None, None)
    single_sort_by_vc_test(["aunt", "engine", "aeiou"], ["aeiou", "engine", "aunt"])
    single_sort_by_vc_test(["aunt", "ENGINE", "aeiou"], ["aeiou", "ENGINE", "aunt"])
test_sort_by_vowel_count()

我需要调试此代码,并且我是python的初学者,所以请帮助

1 个答案:

答案 0 :(得分:2)

您的代码仅计算唯一的元音。如果重复元音(例如public function getFileName() { return $this->hasMany(Filename::className(), ['submitted_by' => 'user_id']); } 中的'e'),您将只计数一次。您未通过测试是因为'engine'有三个元音,但是排序与engine有两个元音(但都是唯一的)相同。由于aunt是稳定的,因此它将始终以与输入中相同的顺序在输出中保留具有相同键值的项(因此list.sort首先结束)。

此问题是由于将'aunt'的长度用于计数而导致的。集合只能包含唯一项,因此您永远都不能以这种方式计算重复项。我不确定您所需要的计数是否有类似的简洁实现,并且没有这个问题。

也许:

set

我要写出我在这里使用的集合中的所有字符,因为Python的编译器(至少在3.6中)能够将这样的集合文字优化为常量(因此它不需要保留在生成器表达式的每次迭代中重新生成集合)。如果您不想依赖于此类特定于实现的优化,则可能需要将集合移到单独的语句中。