V
V
Viva332018-08-04 01:45:37
Python
Viva33, 2018-08-04 01:45:37

Why is the second code faster?

The input is a string s and t, numbers l,r. The essence of the problem is to find the number of occurrences of the string t in a substring of s, where l and r are the numbers of explicit boundaries of the string s. That is, l = 1, r = 3, s = '12345', the searched substring will be '123'. The number m is the length s.
The first version of the code does not pass in time. Why? As I see it, the number of operations in the first option is no more than in the second one, but count() is much faster than a loop with comparisons. Is it so? Which operations are difficult and which are easy in both options?

n, m, q = [int(i) for i in input().split()]
s = input()
t = input()
for i in range(q):
    l,r = map(int, input().split())
    count = 0
    if r - l + 1 >= m:
        for j in range(l-1, r - m + 1):
            if s[j:j + m] == t:           
                count += 1
    print(count)

The second option is faster
n, m, q = [int(i) for i in input().split()]
s = input()
t = input()
positions = ''
for i in range(n-m+1):
    if s[i:i + m] == t:
        positions += '1'
    else:
        positions += '0'
for i in range(q):
    l,r = map(int, input().split())
    if r - l + 1 >= m:
        print (positions[l-1:r-m+1].count('1'))
    else:
        print(0)

Answer the question

In order to leave comments, you need to log in

4 answer(s)
P
Pavlo Ponomarenko, 2018-08-04
@TheShock

At a cursory glance, due to the different complexity of the algorithm. See, in the first loop in the loop - it looks like there's quadratic complexity. The second is linear. Google for these terms.
https://en.wikipedia.org/wiki/%D0%92%D1%8B%D1%87%D...

O
Oleg A., 2018-08-04
@t0rr

Solution in 1 line:
result = s[l-1:r].count(t)

S
Stalker_RED, 2018-08-04
@Stalker_RED

Which operations are difficult and which are easy in both options?
Of course, determining such operations "by eye" is a very cool skill, but it is quite difficult to pump it.
Those who have not yet pumped can use one of the profilers .
The profiler will show you how many times your functions were called, how long each call took, and how long it took in the end.
https://www.youtube.com/watch?v=QJwVYlDzAXs&featur...

S
Sergey Ovsienko, 2018-08-05
@sergovoy

I suggest that you familiarize yourself with my solution to this problem ( https://codeforces.com/contest/1016/problem/B) at the link: https://codeforces.com/contest/1016/submission/41169503
The solution turned out to be the fastest among other solutions on third Python, you can check it here: https://codeforces.com/contest/1016/status/B/page/... (you need to select the Python 3 language in the status filter)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question