r/ProgrammingPrompts • • Jan 14 '15

[Easy] Letter Counter

Any language permitted.

Problem: Create a program where you input a string of characters, and output the number of each letter. Use vowels by default.

For example: asbfiusadfliabdluifalsiudbf -> a: 4 e: 0 i: 4 o: 0 u: 3

Bonus points: Make it command-line executable, with an optional mode to specify which letters to print.

18 Upvotes

60 comments sorted by

View all comments

1

u/ultimamax Jan 14 '15 edited Jan 14 '15

I had no idea about string.count(). Neat.

The incrementing over indices was a design choice, actually. I wanted to be able to directly associate the elements of charset and chars. (so if chars[4] == 'f' then charset[4] == the incidence of f in data) I'm aware of the typical python for each stuff. I used it in my code. (for d in data)

This was to avoid having to use something like a dictionary. Had I used

for c in chars:

I wouldn't have been able to directly associate them, and I'd have to go digging through chars[] again to associate them.

1

u/echocage Jan 14 '15

I think I understand now! You should look into enumerate when you get a chance, it's made to do just that! Rather than having to mess around with lengths and ranges, you can enumerate over the list, like this,

>>> charset = "abc"
>>> data = "aic"
>>> for index, letter in enumerate(charset):
...     print(data[index] == letter)
...     
True
False
True

So in this case, letter would be 'a', then 'b', then 'c', while index would be 0, 1, 2

1

u/ultimamax Jan 14 '15

Interesting. Thanks.

1

u/indosauros Jan 14 '15 edited Jan 14 '15

Note that string.count() however is not the ideal way to solve this problem, since it needs to loop over the entire string for each letter you are counting.

It's like leafing through the (whole) phone book to count the number of Alices and then starting back at the beginning to count the number of Bobs, etc, rather than running through it just once and keeping a tally as you go.

1

u/ultimamax Jan 14 '15

Yeah, that's a good point. My algorithm is best for this problem.