我有这个代码,当输入一个单词时,它应打印出发生次数最少的元音,但它不会打印出元音和最小值。这是我的代码:
#Program to count the least occurring vowels
# take input from the user
w = input("Enter a word or sentence: ")
# string of vowels
vowel = 'aeiouAEIOU'
min_vowel = w[0]
min = w.count(w[0])
# make it suitable for caseless comparisions
w = w.casefold()
count = 0
# count the vowels
for char in w:
if vowel in w:
if w.count(vowel) < min:
min_vowel = w[0]
min = w.count(w)
print ("The least occuring vowel is",min_vowel,"with",min,"occurences.")
请有人告诉我哪里出错了吗?
答案 0 :(得分:2)
如果您希望能够识别出现次数最少的多个元音,我建议使用不同的方法:
from collections import Counter
w = input("Enter a word or sentence: ")
vowel = "aeiouy"
# Count occurences of all vowels.
w = Counter(c for c in w.lower() if c in vowel)
# Get vowels with lowest occurences.
min_values = {k: w[k] for k in w if w[k] == min(w.values())}
# Print vowels.
print("The least occuring vowel is:")
for m in min_values:
print("{vowel} with {occ} occurences.".format(vowel=m, occ=min_values[m]))
示例:
>>> (...)
>>> Enter a word or sentence: Bananas are YUMMY!
The least occuring vowel is:
e with 1 occurences.
u with 1 occurences.