Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/342.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 此解决方案的时间复杂度是否为O(logn)?_Python_Time Complexity_Big O - Fatal编程技术网

Python 此解决方案的时间复杂度是否为O(logn)?

Python 此解决方案的时间复杂度是否为O(logn)?,python,time-complexity,big-o,Python,Time Complexity,Big O,我为一项挑战编写了以下解决方案,但我不确定其时间复杂性: def ASCIIConversion(string): newStr = '' for chr in string: if chr.isspace(): newStr = newStr + ' ' else: newStr += str(ord(chr)) return newStr 程序的复杂性是O(logn),因为els

我为一项挑战编写了以下解决方案,但我不确定其时间复杂性:

def ASCIIConversion(string): 
    newStr = ''

    for chr in string:
        if chr.isspace(): 
            newStr = newStr + ' '
        else:
            newStr += str(ord(chr))

    return newStr
程序的复杂性是O(logn),因为else语句吗?

此解决方案仍然是O(n)。实际上,我不完全确定else语句为什么会影响这一点。您正在对字符串中的每个字符执行一个操作

即使对于每个字符,您要执行多个指令(比较等),您可能会认为复杂性类似于O(3n),但当然您忽略了系数。我相信你知道这一点,但是对于将来看到这个问题、对else语句感到困惑的人来说,这可能会有所帮助。

这个解决方案仍然是O(n)。实际上,我不完全确定else语句为什么会影响这一点。您正在对字符串中的每个字符执行一个操作


即使对于每个字符,您要执行多个指令(比较等),您可能会认为复杂性类似于O(3n),但当然您忽略了系数。我相信你知道这一点,但对于将来看到这个问题的人来说,如果对else语句感到困惑,这可能会有所帮助。

无论if-else条件如何,循环遍历字符串的每个字符,因此时间复杂度为O(n)。

无论if-else条件如何,循环遍历字符串的每个字符,使时间复杂度为O(n)。

最坏情况下的时间复杂度计算如下(假设字符串最大长度为n):

我们假设常数时间为c,因此:

时间复杂度=1+n(c*c+c*c)+1=2+Cn=>O(n)


最坏情况下的时间复杂度计算如下(假设字符串最大长度为n):

我们假设常数时间为c,因此:

时间复杂度=1+n(c*c+c*c)+1=2+Cn=>O(n)


遍历字符串数组,应该是
O(n)
。循环中的所有语句都是常量时间,包括if和else。实际上我现在正在学习大O符号,似乎我有一些误解。非常感谢。遍历字符串数组,应该是
O(n)
。循环中的所有语句都是常量时间,包括if和else。实际上我现在正在学习大O符号,似乎我有一些误解。非常感谢。我现在正在学习大O符号,似乎我有一些误解。谢谢你的详尽回答@没问题!作为一般的经验法则,你可以只计算for和while循环的数量,然后从那里计算出来。实际上我现在正在学习大O符号,似乎我有一些误解。谢谢你的详尽回答@没问题!作为一般的经验法则,您只需计算for和while循环的数量,然后从中计算出来。@TrebuchetMS谢谢。完成:)@TrebuchetMS谢谢。完成:)
newStr = ''  # will be done once so 1 time.

for chr in string: # is iterating on the input with max length of n so n times.
    if chr.isspace(): # will be checked once it is in the loop so 1 time per each iteration.
        newStr = newStr + ' ' # also once per iteration if the if condition is satisfied
    else: # will be chehcked once per iteration
        newStr += str(ord(chr)) # if else is satisfied

return newStr # will be done 1 time.