I have tried to frame a program in Python which would print out the number of times the provided substring appears as a pattern in a provided string.
Unfortunately, my code isn't the best solution as it might not handle some corner cases. I need a solution two-liner or three-liner code maybe) or a modified version to my code.
I also need some suggestions on code optimization if the provided input string is of length 1000 or more.
Input 1:
"XYZDFXYZXY"
"XYZ"
Output 1:
2
Input 2:
"ABCDCDC"
"CDC"
Output 2:
2
My code:
def pattern(string, sub_str ):
counter = 0
len_sub = len(sub_str )
string, sub_str = string.upper(),sub_str.upper()
for i in range(len(string)):
sub_loop = ""
for j in range(i,i+len_sub):
try:
sub_loop+=string[j]
if sub_loop == sub_str:
counter+=1
except:
pass
return counter
if __name__ == '__main__':
string = input().strip()
sub_str = input().strip()
count= pattern(string, sub_str )
print(count)