[英]What is big O notation when a not in string in python
i am trying practice some coding question and wondering how I can calculate big O for following code string[i] in string[i+1:]
and string[i] not in seens
我正在尝试练习一些编码问题,想知道如何为
string[i] in string[i+1:]
和string[i] not in seens
以下代码string[i] in string[i+1:]
计算大O
def findNoCurring(string):
seens = set()
for i in range(len(string)):
if not string[i] in string[i+1:] and string[i] not in seens:
return string[i]
else:
seens.add(string[i])
return None
The line string[i] in string[i+1:]
will make your algorithm O(N^2)
. string[i] in string[i+1:]
将使您的算法为O(N^2)
。 With this line, you're checking every character in the string with every other character. 通过这一行,您将检查字符串中的每个字符以及其他每个字符。 If
string
= "abcd"
, you're checking a
against b
, c
, d
, then b
against c
, d
, and so on. 如果
string
= "abcd"
你检查a
对b
, c
, d
,则b
对c
, d
,等等。 the line string[i] not in seens
will be O(1) on average since Python sets are implemented something like dictionaries (see the answer here ). 由于Python集的实现类似于字典(请参见此处的答案),因此
string[i] not in seens
平均为O(1)。
Note that the in
operation for Python lists, is, on average, O(N)
. 请注意,Python列表的
in
操作平均为O(N)
。 See this 看到这个
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.