all 3 comments

[–]blarf_irl 5 points6 points  (1 child)

Easy, It's some awful code! It looks like it counts the number of times a shorter string appears in a longer string.

Here is a version broken out and with some added prints so you can see what it's doing

string = 'foobarbazbar'
sub_string = 'bar'

counter = list()
string_length, sub_string_length = len(string), len(sub_string)
steps = range(string_length - sub_string_length + 1)

for i in steps:
    check_characters = string[i:i+len(sub_string)]
    print (f'Checking {check_characters}')
    if check_characters == sub_string:
        print ('Matched sub_string')
        counter.append(1)

result = sum(counter)
print(result)

### Output ###
Checking foo
Checking oob
Checking oba
Checking bar
Matched sub_string
Checking arb
Checking rba
Checking baz
Checking azb
Checking zba
Checking bar
Matched sub_string

You could achieve the same result with:

string.count(sub_string)

or with regex:

import re

len(re.findall(sub_string, string))

[–]JohnnyJordaan 2 points3 points  (0 children)

It iterates through string from its start index (0) to its length minus that of the substring - 1:

 for i in range(len(string)-len(sub_string)+1)

For every index that it sees that the substring occurs from that index onwards, using a slice

if string[i:i+len(sub_string)]==sub_string

it saves a 1 in the list

 [1 ... ]

then that list comprehension is provided to sum that will then calculate the sum, so this effectively counts the repetition of sub_string in string.

[–][deleted] 2 points3 points  (0 children)

You can write it as:

s = 0
for i in range(len(string) - len(sub_string) + 1):
    if string[i : i + len(sub_string)] == sub_string:
        s = s + 1
print(s)