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. The code runs fine for n untill 3, but shows memory error for 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)

Upvotes: 0

Views: 57

Answers (2)

zwer
zwer

Reputation: 25769

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, i.e.:

def largestProduct(n):
    return (10**n-1)**2

Upvotes: 3

criskross
criskross

Reputation: 84

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

Upvotes: 2

Related Questions