Complexity of len() with regard to sets and lists

前端 未结 7 1302
耶瑟儿~
耶瑟儿~ 2021-02-04 23:38

The complexity of len() with regards to sets and lists is equally O(1). How come it takes more time to process sets?

~$ python -m timeit \"a=[1,2,3,         


        
7条回答
  •  生来不讨喜
    2021-02-05 00:25

    Let me compound the excellent answers here: O(1) only tells you about the order of growth with respect to the size of the input.

    O(1) in particular only means constant time with respect to the size of input. A method may always take 0.1s, for any input, and another may take 1000 years for any input, and they'd both be O(1)

    In this case, while the documentation has some degree of ambiguity, it means that the method takes roughly the same time to process a list of size 1 as it takes to process list of size 1000; similarly, it takes the same time to process a dictionary of size 1 as it takes to process a dictionary of size 1000.

    No guarantee is given with respect to different data types.

    This is unsurprising since the implementation of len() at some point down the call stack can differ depending on the data type.

    Incidentally, this ambiguity is eliminated in statically typed languages where ClassA.size() and ClassB.size() are for all intents and purpouses two different methods.

提交回复
热议问题