简体   繁体   English

打印列表的时间复杂度

[英]Time Complexity of printing a list

Here are 2 different codes performing the same function that is printing a list.这是执行相同 function 打印列表的 2 个不同代码。

  • code-1代码-1
list1=[5,4,86,2,4,5,3,4]
for i in list1:
    print(i,end=" ")
  • code-2代码 2
list1=[5,4,86,2,4,5,3,4]
print(list1)

Can I say that printing a list has a time complexity of O(n)?我可以说打印列表的时间复杂度为 O(n) 吗? While calculating the time complexity of any program we don't consider the time complexity of printing statements as it takes order of 1 but as in the code-1 it takes order of n.在计算任何程序的时间复杂度时,我们不考虑打印语句的时间复杂度,因为它需要 1 的顺序,但在code-1中它需要 n 的顺序。

I am an introvert in Python.我是 Python 的内向者。 So if possible please also share the backend implementation of print(list) or else if any article or blog on it.因此,如果可能的话,请分享print(list)的后端实现,或者如果有任何文章或博客。

The output is different, but that's not important. output 不同,但这并不重要。

Either method is O(n) .任何一种方法都是O(n)

In the first case each element of the list is visited once hence O(n) .在第一种情况下,列表的每个元素都被访问一次,因此O(n)

In the second case the print() function itself iterates over the list visiting each element once, also O(n) .在第二种情况下, print() function 本身遍历列表访问每个元素一次,也是O(n)

If you really want to you can read the code in the Python source code repository.如果你真的想要,你可以阅读Python 源代码库中的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM