Z
Z
zlodiak2019-02-21 23:12:31
Python
zlodiak, 2019-02-21 23:12:31

Is it necessary to increase the complexity?

Please tell me, I understand correctly that in order to determine the complexity of the following algorithm, you need O (n) * O (n) = O (n ^ 2)

#!/usr/bin/env python3

def reverse_letter(string):
    return ''.join([l for l in reversed(string) if l.isalpha()])

I do this because reverse will iterate over all elements in the worst case, and for will also iterate over all elements. Thus, the final complexity will be quadratic

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman Kitaev, 2019-02-21
@zlodiak

No. Now, if you had two nested loops on string, then yes. And here the complexity "adds up", because first O (n) - reverse, then O (n) - creating a cycle, then O (n) - join. But since no one needs constants in complexity - it's only O (n)
But, of course, you won't believe it, so here's the proof for you. Time grows linearly with N
5c6f07ce35b63943246212.png

P
Pavlo Ponomarenko, 2019-02-21
@TheShock

If I understand correctly, reversed will only happen once. In pseudocode, you can write it like this:

newStr = reversed(string);
for sym in newStr; // ..

That is, a linear pass is used here twice, and not a linear one inside a linear one, which means that there is no need to multiply - the complexity is linear.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question