Home > OS >  What is wrong in my finding frequency of substring in a strng
What is wrong in my finding frequency of substring in a strng

Time:10-15

I am trying to find the no. of occurrence of a substring in a string. I know that count function can be used but it is for non-overlapping occurrences.

Here is my code I found online

string = input("Enter the string: ");
sub_string = input("Enter the substring: ")
count = 0

for i in range(0, len(string)):
    for j in range(0, len(sub_string)):
        if string[i] == sub_string[j]:
            j  = 1
        else:
            j = 0
    if j == len(sub_string):
        count  = 1

print(count)

In this, in the 2nd loop we compare each element of sub_string[j] to string[i] which is same in that loop, then how j will increase & increase the count after checking in next if condition.

Output of code

CodePudding user response:

So the code you have is wrong, since it would pass the if check as long as the last character matches the matches the string, e.g. string "sagar is sagar not sa saga sagar r" and substring "sagar" would return 4 rather than 3.

Since you use j both to count the number of matches as well as the index for the substring, it gets overwritten in the inner loop each iteration. This means that it would only need to match the very last letter to pass the check below the loop.

You might want to change it to something that checks each character starting at some position and denies it if it doesn't match, e.g.

string = input("Enter the string: ");
sub_string = input("Enter the substring: ")
count = 0

for i in range(0, len(string) - len(sub_string)):
    found = True
    for j in range(len(sub_string)):
        if string[i   j] != sub_string[j]:
            found = False
            break
    if found:
        count  = 1

CodePudding user response:

In your case only the last elements are equal then the count will increment by one.

for ex: if string is seg, and sub string is sag the the count will be one. this happens because in the second loop when j = len(substring)-1, g from seg and sag will be detected as equal. so then count get increment by one.

string = input("Enter the string: ");
sub_string = input("Enter the substring: ")
count = 0

for i in range(0, len(string)):
    j=0
    while i j< len(string) and  j <len(sub_string):
        if string[i j] == sub_string[j]:
            j  = 1
        else:
            break
    else:
        count  = 1

print(count)

try this code, in there if while loop didn't get break count increment by one.

  • Related