简体   繁体   中英

How to optimize this code to reduce memory usage?

My below code uses more than 300000 KB using about(30000 input element) and there is a limit per memory usage(256 MB), so is there any way to optimize it?

import itertools
def get_subsets(arr,m) :
    return list(itertools.combinations(arr,m))
def _9(string) :
    count =0
    for i in range(len(string)-1 , -1 ,-1) :
        if string[i] != '9' :
            break
        count += 1
    return count
if __name__ == "__main__" :
    length = int(input())
    arr = [int(x) for x in input().strip().split()]
    pairs = get_subsets(arr,2)
    max_9 = [_9(str(x[0]+x[1])) for x in pairs]
    max_9_0 = max(max_9)  
    print(max_9_0,max_9.count(max_9_0))

The problem is: Let's define the quality of the price as the number of nines at its end (the number of rightmost digits that are equal to 9). For example, numbers 2999 and 123912391999 both have the quality 3, while number 952 has quality 0.

There are n products with distinct prices t1, t2, ..., tn.

You're going to buy exactly two products (they must be different). Please find the maximum possible quality of the total price of two chosen products. Also, find the number of ways to choose two different products and get that maximum possible quality of the total price.

One way might be instead of using lists. Use generators. They are iterable too. See: http://letstalkdata.com/2015/05/how-to-use-python-generators-to-save-memory/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM