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.
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:A more Pythonic solution would be something like this: