I am trying to complete a coding challenge which requires me to count all of the digits between 1 and X, where can reach up to 400,000,000,000,000,000
My approach was to iterate over a list and add the amount of digits to my result in the end, like so:
def page_digits(pages):
list_of_pages = list(range(1, pages + 1))
res = 0
for num in list_of_pages:
res += len((str(num)))
return res
Run Code Online (Sandbox Code Playgroud)
but obviously creating a list of every digit between 1 and that big number requires a lot of storage and running this returns 'MemoryError Line 2'
How else could I go about this? or Avoid the problem
您没有理由需要将范围转换为列表。
>>> def page_digits(pages):
... res = 0
... for num in range(1, pages + 1):
... res += len(str(num))
... return res
...
>>> page_digits(100000)
488895
Run Code Online (Sandbox Code Playgroud)
调用list构造函数会强制将范围中的每个元素单独存储在内存中,但常规range对象非常节省内存(它只包含您在构造时传递给它的参数),同时仍然是可迭代的。
您可能需要将范围转换为列表的唯一原因是更改其中的各个元素(您不能对范围执行此操作)。