1

I am trying to solve a more generic problem similar to the following. In the following, I get vow_array, which indicates the presence of a subset of vowels in some text, say, sent to my program. I need to print each vowel's presence as 0 or 1.

ch_a = 0 ch_e = 0 ch_i = 0 ch_o = 0 ch_u = 0 # vow_array is generated at runtime; here is an example vow_array = ['a', 'o', 'u'] if 'a' in vow_array: ch_a = ch_a + 1 if 'e' in vow_array: ch_e = ch_e + 1 if 'i' in vow_array: ch_i = ch_i + 1 if 'o' in vow_array: ch_o = ch_o + 1 if 'u' in vow_array: ch_u = ch_u + 1 print ch_a, ch_e, ch_i, ch_o, ch_u 

I think this code is too long and prone to errors. Is there a more compact way of writing this? Also, say if I had to do this for all 'letters' in the alphabet I don't want to have to repeat the code.

3 Answers 3

6

Definitely.

If you ever have variables with the same prefix (ch_a, ch_e, ...), you need to use a dictionary or a list to group them:

vowels = { 'a': 0, 'e': 0, 'i': 0, 'o': 0, 'u': 0 } vowel_array = ['a', 'o', 'u'] for vowel in vowels.keys(): if vowel in vowel_array: vowels[vowel] += 1 print vowels 

A more Pythonic solution would be something like this:

>>> from collections import Counter >>> >>> letters = 'i am a sentence' >>> Counter(letters) Counter({' ': 3, 'e': 3, 'a': 2, 'n': 2, 'c': 1, 'i': 1, 'm': 1, 's': 1, 't': 1}) 
Sign up to request clarification or add additional context in comments.

2 Comments

+1 - Data structures are what is missing, and collections.Counter is the right move here.
Beautiful, thank you! Thanks to others, too, with same idea for the solution.
1

Same idea as @Blender's, just with a different way of initializing the dictionary (you can do this with a dict comprehension in Python >2.7):

>>> vowels = dict((v, 0) for v in 'aeiou') >>> vow_array = ['a', 'o', 'u'] >>> for vow in vow_array: ... vowels[vow] += 1 >>> vowels {'e': 0, 'i': 0, 'o': 1, 'u': 1, 'a': 1} 

And if sorting it is a concern:

>>> for value in sorted(vowels): ... print '{0}: {1}'.format(value, vowels[value]) ... a: 1 e: 0 i: 0 o: 1 u: 1 

Comments

0

try this:

ch_dict = {'a':0,'e':0,'i':0,'o':0,'u':0} vow_array = ['a','o','u'] for d in vow_array: ch_dict[d] = ch_dict[d] + 1 print(ch_dict) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.