简体   繁体   English

写元音计数器

[英]Writing a vowel counter

This is my homework assignment: 这是我的作业:

Write function vowelCount() that takes a string as input and counts and prints the number of occurrences of vowels in the string. 编写函数vowelCount(),该函数将字符串作为输入并计算并打印字符串中元音出现的次数。

vowelCount ( ' Le Tour de France ' ) a, e, i, o, and u appear, respectively, 1, 3, 0, 1, 1 times. vowelCount(“环法自行车赛”)a,e,i,o和u分别出现1、3、0、1、1次。

This is what I've done so far and it's not working! 到目前为止,这是我所做的,但是没有用! What do I do? 我该怎么办?

def vowelCount(sentence):
    sentence = sentence.lower()
    vowels = "aeiou"
    count = 0
    if vowels in sentence:
        count = +1
        print("a, e, i, o, u, appear, respectively," count "times.")

I'm so bad with Python that I can never do my homework on my own. 我对Python很不满意,以至于我永远无法独自完成作业。 I might as well just give up trying to learn. 我最好还是放弃尝试学习。

You are doing wrong initialization. 您正在执行错误的初始化。

vowels = "aeiou"

You should declare it as list or dictionary. 您应该将其声明为列表或字典。 Now the problem with your solution is that you are checking if "vowels" which you have initialized as "aeiou" is present in incoming string or not 现在,解决方案的问题是您正在检查传入字符串中是否存在已初始化为“ aeiou”的“元音”

if vowels in sentence:

So here you are checking that "aeiou", the whole string is present in the incoming sentence or not. 因此,在这里您要检查输入的句子中是否存在整个字符串“ aeiou”。 You are not checking for individual vowel and individual character. 您不检查单个元音和单个字符。

The solution will we like iterating all over the sentence from 0 to n-1 where n is its length and check each character. 该解决方案将需要遍历从0到n-1的整个句子,其中n是其长度,并检查每个字符。

 def count(string):
    #we use hashmap to make lookup operation cheap
    mp = {'a':1,'e':1,'i':1,'o':1,'u':1}
    n = len(s)
    count = 0
    for i in range(n):  #iterating for every element in string
        if s[i] in mp:   #checking if it is vowel or not
            count += 1
    return count

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM