Counting specific letters within an array
An answer to this question on Stack Overflow.
Question
I am asked to create a function in which it counts all the leters from b-s within a string. Here is what i have so far:
def strange_count(s):
count = 0
s = s.lower()
s_count = [b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s]
while count <= len(s):
for i in range(len(s_count)):
if s_count[i] == s[count]:
count += 1
return
It is returning an error, any help would be greatly appreciated
File "", line 4, in strange_count
s_count = [b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s]
NameError: name 'b' is not defined
Answer
This line:
s_count = [b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s]
should be like this:
s_count = ["b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s"]
Then you'll find that you're in an infinite loop, so try rewriting like this:
def strange_count(s):
count = 0
s = s.lower()
s_count = ["b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s"]
for letter in s:
if letter in s_count:
count += 1
return count
print(strange_count("asfdsjfdlkwjrwoiureaoifhwabrejwer"))