[英]How can I improve my code to avoid memory based error?
I wrote a python function largestProduct(n)
which returns the largest number made from product of two n-digit numbers. 我编写了一个python函数largestProduct(n)
,该函数返回由两个n位数字的乘积组成的最大数字。 The code runs fine for n
untill 3, but shows memory error for n>3
. 该代码对于n
直到3都可以正常运行,但是对于n>3
显示内存错误。 Is there a way I can improve my code to avoid this error? 有没有一种方法可以改进我的代码来避免此错误?
def largestProduct(n):
number_lst = []
prod_lst = []
count = 0
for i in range(10**(n-1),(10**n)):
number_lst.append(i)
while count!= len(number_lst):
for i in range(len(number_lst)):
prod_lst.append(number_lst[count]*number_lst[i])
count +=1
prod_set = list(set(prod_lst))
return max(prod_lst)
Well, you don't need any storage to loop through what you need: 好吧,您不需要任何存储来遍历所需的内容:
def largestProduct(n):
range_low = 10**(n-1)
range_high = 10**n
largest = 0
# replace xrange with range for Python 3.x
for i in xrange(range_low, range_high):
for j in xrange(range_low, range_high):
largest = max(largest, i*j)
return largest
But why would you want to do this? 但是为什么要这么做呢? The largest product of two n -long numbers is always the largest number you can write with n digits squared, ie: 两个n长数字的最大乘积始终是您可以写成n位数字平方的最大数字,即:
def largestProduct(n):
return (10**n-1)**2
You should consider creating a generator function. 您应该考虑创建一个生成器函数。 In the end you can iterate over the output of your function which only processes each element one by one instead of holding the whole list in memory. 最后,您可以遍历函数的输出,该函数仅一个一个地处理每个元素,而不是将整个列表保存在内存中。
see https://wiki.python.org/moin/Generators 参见https://wiki.python.org/moin/Generators
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.