0

I am trying to count the number of times letters show up in a string, so i'm using the count() function which is working fine, however using multiple count() functions seems tedious since i'm trying to count 10+ letters.

def printer_error(s):
 #errorLetters = ('r','s','t','u','v','w','x','y','z')
 errorRate = s.count('o') + s.count('p') + s.count('q')


 print(errorRate)
 return 

printer_error('aaaxbbbbyyhwawiwjjjwwm')

My first attempt was s.count(errorLetters) but that failed because the count() function can't take tuples or lists.

the current code is giving me the result I want but I still have to concatenate the rest of those commented out letters in the errorLetters variable, is there another way to do this that doesn't involve making 20+ concatenations?

3
  • The errorRate variable listed currently doesn't count anything because I wanted to keep it alphabetical, but I texted it beforehand with 'w' and 'y' and got the result I wanted. Commented May 23, 2017 at 22:02
  • It's a shame we can't downvote on comments. @ewcz proposal is not good, it's needlessly inefficient to use s.count inside the loop. Commented May 23, 2017 at 22:07
  • @wim fair enough ;) sum([1 if c in errorLetters else 0 for c in s]) Commented May 23, 2017 at 22:19

1 Answer 1

2

The best way to do this only requires to iterate s once, i.e. O(n).

Standard library collections module provides a Counter object that will be useful and efficient:

>>> s = 'aaaxbbbbyyhwawiwjjjwwm'
>>> errorLetters = ('r','s','t','u','v','w','x','y','z')
>>> from collections import Counter
>>> counts = Counter(s)
>>> sum(counts[k] for k in errorLetters)
8
Sign up to request clarification or add additional context in comments.

1 Comment

There are a ton of useful libraries this is works great

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.