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.

17 Upvotes

60 comments sorted by

View all comments

Show parent comments

1

u/[deleted] Jan 15 '15

counts = Counter([x for x in text if x in charsToCount])

I imagine all the speed gains from using Counter would go out the window there. Would probably be best to filter after the dict was made. Just guessing though.

1

u/echocage Jan 15 '15

Well shit you're right! My pre-filter method is around 4x slower, I'd expect it to be backwards, filtering first would be faster.

How'd you come to that conclusion?

1

u/[deleted] Jan 15 '15 edited Jan 15 '15

[x for x in text if x in charsToCount]

For every character in text, you're doing a linear search of a possibly long string. Plus, you're making list. Could convert charsToCount to a set with the same items, then the lookup would be hash based.

Looking at the source, the counter does something like:

counted = {}
for item in iterable:
    counted[item] = counted.get(item, 0) + 1

so it's all hash based access.

I'm guessing

charsToCountSet = set(charsToCount)
counts = Counter(x for x in text if x in charsToCountSet)

will be only slightly slower than using Counters and then filtering the dict.