[Tutor] Ideas on making this cleaner?
Mats Wichmann
mats at wichmann.us
Sat May 4 13:51:12 EDT 2024
On 5/4/24 11:32, ThreeBlindQuarks via Tutor wrote:
>
>
> Leam,
>
> I some cases, a dictionary is a useful method to consolidate multiple cases.
>
> For example, your vowels:
>> self.syllable_count += line.count("a")
>> self.syllable_count += line.count("e")
>> self.syllable_count += line.count("i")
>> self.syllable_count += line.count("o")
>> self.syllable_count += line.count("u")
>> self.syllable_count -= line.count("ee")
>> self.syllable_count -= line.count("oi")
>> self.syllable_count -= line.count("oo")
>> self.syllable_count -= line.count("ou")
>
> You could initialize a dictionary like Vowels with keys like "a" through "ou" initialized to zero and increment it when a vowel is encountered.
In fact, the stdlib Counter class can be helpful in such usage:
https://docs.python.org/3/library/collections.html#counter-objects
More information about the Tutor
mailing list