The number of characters in chars1 / chars2 that occur in s
This makes sense as you grow with the if condition . Since if not in a loop, you can increment it once.
Now we can deploy the generator in a for loop . This will solve one part of the problem and generate 0/6 :
for c in chars1: if c in s: counter1 += 1 for c in chars2: if c in s: counter2 += 1
However, this still will not be terribly effective: in order to check if a character is in a string, O (n) worst case is required. You can first build a set with characters in a string, and then do a search (usually this is O (1) in the middle case:
def error_printer(s): sset = set(s) chars1 = "abcdefghijklm" chars2 = "nopqrstuvwxyz" counter1 = 0 counter2 = 0 for c in chars1: if c in sset : counter1 += 1 for c in chars2: if c in sset : counter2 += 1 print(str(counter2) + "/" + str(counter1))
Now we have improved the efficiency, but still not very elegant: it takes a lot of code, and in addition, you need to check the code to know what it does. We can use the sum(..) construct to calculate the number of elements that satisfy a certain constraint, for example:
def error_printer(s): sset = set(s) chars1 = "abcdefghijklm" chars2 = "nopqrstuvwxyz" counter1 = sum(c in sset for c in chars1) counter2 = sum(c in sset for c in chars2) print(str(counter2) + "/" + str(counter1))
This creates 0/6 , because in the range [AM] there are six characters in s and 0 in the range [NZ] that occur in s .
The number of characters in s that occur in char1 / char2
However, based on the main question, you want to count the number of characters in s that occur in two different ranges .
Another related issue is counting the number of characters encountered in char1 / char2 . In this case, we just need to swap the loops :
def error_printer(s): chars1 = set( "abcdefghijklm" ) chars2 = set( "nopqrstuvwxyz" ) counter1 = sum(c in chars1 for c in s ) counter2 = sum(c in chars2 for c in s ) print(str(counter2) + "/" + str(counter1))
This creates 0/14 , since s has 14 characters that occur in the range [AM] (if 'a' occurs twice in s , then we count it twice) and none of the characters in s occur in the range [NZ] .
Using Range Checks
Since we work with ranges , we can use comparisons instead of element checks and run them with two comparisons, for example:
def error_printer(s): counter1 = sum( 'a' <= c <= 'm' for c in s) counter2 = sum( 'n' <= c <= 'z' for c in s) print(str(counter2) + "/" + str(counter1))