My own implementation of count function
The count function in Python gets some corner cases wrong and therefore we can't use it everywhere, so I thought of implementing my own. It handles all the corner cases in my opinion, but maybe you can try your own cases and test it.
The problem was coming for cases like the string "Banana" if we search for the count of substr "ana" in it, then we would get answer as 1 but it should be 2.
Now I will use it in the Minion Game problem of HackerRank.
'''Implementing My Own Count Function'''
def count(s:str,st:str)->int:
'''
s: The string in which we have to search the count of 'st'
st: The string whose count we need to get in 's'
Returns: The number of times st was in s, it's count
'''
# Sample Case: s->cdababa, st->'aba',count should
# be 2 not 1(as given by the count function of Python)
# To traverse in st
itr=0
# The main count variable
count=0
# The sizes of both the strings
n1=len(s)
n2=len(st)
#Just access every element of s
for i in range(n1):
chk=1
if s[i]==st[0]:
print(f"{s[i]} at index {i} of s is equal to {st[0]} at"
" index {0} of st. ")
itr=i
for j in range(n2):
if itr<n1 and s[itr]!=st[j]:
chk=0
break
if itr==n1-1 and j!=n2-1:
# When s is done but st was still
# left to be traversed
chk=0
itr+=1
if chk==1:
#Means st is in s
count+=1
print(f"The count of the string {st} in {s} is {count}.")
return count
print(count("banana","an"))
Comments
Post a Comment