简体   繁体   English

如何改善代码以避免基于内存的错误?

[英]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.

相关问题 我如何在我的python代码中避免此错误 - How can i avoid this error in my python code 如何分析或改进我的侄女基于摩尔斯电码的简单压缩算法? - How can I analyze or improve my niece's simple compression algorithm that is based on Morse code? 如何改善功能以提高内存效率? - How can I improve my function to be more memory efficient? 如何改善代码以处理大量数字? - How can I improve my code to handle large numbers? "抓取数据 PRAW - 如何改进我的代码?" - Scraping data PRAW - How can I improve my code? 如何改进 euler 14 的代码? - How can I improve my code for euler 14? 我该如何改进这段代码? - How can I improve this code? 当我改变我正在迭代的列表时,如何避免代码中的列表错误功能? - How can I avoid the list error function in my code as I alter a list I am iterating? 如何避免在此递归函数中使用全局变量并改善代码? - How to avoid using a global variable in this recursion function and improve my code? 我有一个 400 万行的 DataFrame 并尝试将一列值从字符串转换为 JSON 并遇到 memory 问题。 如何改进我的代码? - I have a DataFrame of 4 mln rows and try to convert one column values from string to JSON and got memory problem. How can I improve my code?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM