Reputation: 49
I have managed to code this :
def vowels(s) :
result = 0
n = 0
while n<len(s):
if s[n] in "AEIOUaeiou" : result = result+1
n = n+1
return result
line = input("Type a line of text: ")
print("The line contains", vowels(line), "vowels")
which gives me how many vowels in total are in line.. But i want to know how to change it so it will output the vowel(s) which occurred most frequently and how many times it occured
Upvotes: 4
Views: 595
Reputation: 11596
Make use of collections.Counter
and its most_common
method
from collections import Counter
def vowels(s) :
vow_found = [i for i in s.lower() if i in 'aeiou']
c = Counter(vow_found)
return len(vow_found), c.most_common()
line = input("Type a line of text: ")
numvow, most_com = vowels(line)
print("The line contains", numvow, "vowels")
print("and the most common are", most_com)
which, with an input of
hello I am your friend today
produces
The line contains 10 vowels
and the most common are [('o', 3), ('i', 2), ('a', 2), ('e', 2), ('u', 1)]
Upvotes: 1
Reputation: 22292
You can use collections.Counter
to do this:
import collections
vowels = lambda s: collections.Counter(i for i in s if i in 'AEIOUaeiou').most_common(1)[0]
line = input("Type a line of text: ")
v = vowels(line)
print("The most frequently vowel is", v[0], 'the times is', v[1])
Upvotes: 0
Reputation: 52193
You can use collections.Counter
to get the count of occurrence of each vowel in the text.
>>> from collections import Counter
>>> def vowels(s):
... return Counter(c for c in s if c in "AEIOUaeiou")
>>> counter = vowels("Lorem ipsum lorem")
>>> print counter
Counter({'e': 2, 'o': 2, 'i': 1, 'u': 1})
>>> print sum(counter.values())
6
>>> print counter.most_common()
[('e', 2), ('o', 2), ('i', 1), ('u', 1)]
Upvotes: 1
Reputation: 4499
A shorter simpler code for the same
from collections import Counter
def most_common_vowel(input_string):
return Counter(
filter(lambda x: x in "aeiou", input_string.lower())
).most_common(1)
Use filter
function to remove non-vowels from string and the use Counter
to get most common element
Upvotes: 0
Reputation: 11144
What my approach does:
lower()
to make the input lowercase.Hope this helps:
line = input("Type a line of text: ").lower()
print(sorted([(i,line.count(i)) for i in "aeiou"], key=lambda x:x[1], reverse=True)[0])
Upvotes: 0
Reputation: 1711
def vowels(s) :
vowel_letters = "AEIOUaeiou"
result = []
for vowel in vowel_letters:
result.append((vowel,s.count(vowel)))
result.sort(key=lambda tup: tup[1])
return result[-1]
line = raw_input("Type a line of text: ")
print vowels(line)
Upvotes: 0