简体   繁体   中英

how to make vowel counter and sum more concise and efficient? Python

I am new to Stack Overflow, but noticed how helpful, and open this community is. Just curious if there is anyway to make this vowel counter more concise/organized. Any help would be appreciated, and an in-depth answer would be awesome as well. Thank you!

def vowel_count(str):

    str = input("Please enter a sentence: ")
    str1 = (str.lower())
    #intialize count variable to zero
    count = 0

    #create a set of vowels
    vowel = set("aeiou")

    for alphabet in str1:
        if alphabet in vowel:
            count = count+1

    print("Number of vowels in this sentence is: " , count)
    print()
    print("A,E,I,O,U")
    print(*map(str.lower().count, "aeiou"))

vowel_count(str)    

I see that in your code example, you used a variable named str. Don't do that, as str is a built-in function and this can lead to problems.

What about this solution:

string = input().lower()

print(sum([string.count(i) for i in "aeiou"]))

Firstly, I get the input, which I lower immediately. Then, I used the string.count(i) for every vowel, which in this case returns the amount of times i (one of the vowels) appears in the string (input). I then called the sum function on the created array which returns the sum of all elements inside the array. Last but not least, I simply printed the value returned from this sum function.

If you don't understand how the argument passed to the sum function is an array, look into the topic of List Comprehension .

I think you should use Counter .

from collections import Counter
In [1]: a = 'I am mayank'
In [5]: ans = Counter(a.lower())

In [6]: ans
Out[6]: Counter({' ': 2, 'a': 3, 'i': 1, 'k': 1, 'm': 2, 'n': 1, 'y': 1})

In [10]: ans['a']
Out[10]: 3

This will count the occurrence of each letter in the string including vowels. This should be quite efficient.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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