The problem
The aim of this problem is to put in writing a perform that takes two inputs: a string and a personality. The perform will rely the variety of occasions that character seems within the string. The rely is case insensitive.
Examples:
count_char("fizzbuzz","z") # 4
count_char("Fancy fifth fly aloof","f") # 5
The character may be any alphanumeric character.
The answer in Python code
Choice 1:
def count_char(haystack, needle):
rely = 0
for c in haystack:
if c.decrease()==needle.decrease():
rely+=1
return rely
Choice 2:
def count_char(s,c):
return s.decrease().rely(c.decrease())
Choice 3:
from collections import Counter
def count_char(s, c):
return Counter(s.decrease())[c.lower()]
Take a look at instances to validate our answer
check.assert_equals(count_char("Hi there there", "e"), 3)
check.assert_equals(count_char("Hi there there", "t"), 1)
check.assert_equals(count_char("Hi there there", "h"), 2)
check.assert_equals(count_char("Hi there there", "L"), 2)
check.assert_equals(count_char("Hi there there", " "), 1)