Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
62 views
in Technique[技术] by (71.8m points)

python - What time complexity does the following code have?

I am confused with the time complexity of the following code and I need all the help I can get because I'm struggling to figure it out.

The code goes as follows:

def herhalen(s,p):
    pc = 0
    while pc < len(s):
       pd = pc + 1
       while pd < len(s):
          if s[pd] == s[pc]:
             x = 0
             while pd + x < len(s) and x < p and s[pc + x] == s[pd + x]:
                x += 1
             if x ==p:
                return True
          pd += 1
       pc += 1
    return False
question from:https://stackoverflow.com/questions/65890565/what-time-complexity-does-the-following-code-have

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It depends on the elements of s. If, for instance, all elements of s are equal, then your condition if s[pd] == s[pc] will always be true, which will in turn affect the overall complexity. If, however, all elements of s are distinct, then s[pd] == s[pc] will only be true when the pd and pc hold the same value and therefore pointing to the same element in s.

Example 1 - Unique elements

s = [i for i in range(20)] #[0,1,2,...,19]
pc = 0
while pc < len(s):
    pd = pc + 1
    while pd < len(s):
        if s[pd] == s[pc]:
            print(pd)
        pd += 1
    pc += 1

In this scenario, the print function is never executed.

Example 2 - Identical elements

s = [0 for i in range(20)] #[0,0,...,0]
pc = 0
print_counter = 1
while pc < len(s):
    pd = pc + 1
    while pd < len(s):
        if s[pd] == s[pc]:
            print(print_counter)
            print_counter += 1
        pd += 1
    pc += 1

In this scenario, the print function got executed 190 times which is O(n^2).

Note

  • Note that for your code, you have an additional loop that you have to consider.
  • Also note that there exist more scenarios where the elements of s are neither all equal or all unique.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...