Sequence Of Vowels Count
Solution 1:
I find regular expressions natural for this question. (I think a non-regex answer would take more coding. I use two string methods, 'lower' and 'endswith' to make the answer more clear.)
import re
defsyllables(word):
word = word.lower()
if word.endswith('e'):
word = word[:-1]
count = len(re.findall('[aeiou]+', word))
return count
for word in ('honour', 'decode', 'decodes', 'oiseau', 'pie'):
print word, syllables(word)
Which prints:
honour 2
decode 2
decodes 3
oiseau 2
pie 1
Note that 'decodes' has one more syllable than 'decode' (which is strange, but fits your definition).
Question. How does this help you? Isn't the point of the study question that you work through it yourself? You may get more benefit in the future by posting a failed attempt in your question, so you can learn exactly where you are lacking.
Solution 2:
Use regexps - most languages will let you count the number of matches of a regexp in a string.
Then special-case the terminal-e by checking the right-most match group.
Solution 3:
I don't think regex is the right solution here.
It seems pretty straightforward to write this treating each string as a list.
Solution 4:
Some pointers:
[abc]
matches a
, b
or c
.
A +
after a regex token allows the token to match once or more
$
matches the end of the string.
(?<=x)
matches the current position only if the previous character is an x
.
(?!x)
matches the current position only if the next character is not an x
.
EDIT:
I just saw your comment that since this is not homework, actual code is requested. Well, then:
[aeiou]+(?!(?<=e)$)
If you don't want to count final vowel sequences that end in e
at all (like the u
in tongue
or the o
in toe
), then use
[aeiou]+(?=[^aeiou])|[aeiou]*[aiou]$
I'm sure you'll be able to figure out how it works if you read the explanation above.
Solution 5:
Here's an answer without regular expressions. My real answer (also posted) uses regular expressions. Untested code:
defsyllables(word):
word = word.lower()
if word.endswith('e'):
word = word[:-1]
vowels = 'aeiou'
in_vowel_group = False
vowel_groups = 0for letter in word:
if letter in vowels:
ifnot in_vowel_group:
in_vowel_group = True
vowel_groups += 1else:
in_vowel_group = Falsereturn vowel_groups
Post a Comment for "Sequence Of Vowels Count"