Time and Space Complexity of list to str conversion in Python

落花浮王杯 提交于 2019-12-23 23:18:29

问题


Trying to find out what is the time complexity of casting to string

str([1,2,6,...,3,6])

Pretty sure it's O(1) Not sure how to verify.

Edit: about space complexity, That should not be linear to list size, thinking O(1) because string has max size.


回答1:


It's linear, because bigger lists need more time and memory to convert.

Graph generated using perfplot. Code, for reference:

import numpy as np
import perfplot 

perfplot.show(
    setup=lambda n: np.random.choice(100, n).tolist(),
    kernels=[
        lambda lst: [str(x) for x in lst],
        lambda lst: list(map(str, lst)),
    ],
    labels=['[str(x) for x in lst]', 'list(map(str, lst))'],
    n_range=[2**k for k in range(0, 20)],
    xlabel='N',
    logx=True,
    logy=True,
    equality_check=None)


来源:https://stackoverflow.com/questions/45657710/time-and-space-complexity-of-list-to-str-conversion-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!