简体   繁体   English

组合python非常大的列表

[英]List of combination python very large numbers

I need a list of all possible combinations of k out of n numbers for very large n. 对于非常大的n,我需要列出n个数字中k个所有可能组合的列表。 I run into the problem of my list size exceeding 500000 quickly, which python does not seem to handle very well. 我遇到了我的列表大小迅速超过500000的问题,而python似乎处理得不太好。 However, I would like to exceed that by hundreds of millions. 但是,我想超越这个数亿。 How do I handle that? 我该如何处理? Thanks a lot! 非常感谢!

DP won't work for very large number because storing such large size list would result in MemoryError . DP不能用于很大的数字,因为存储如此大的列表会导致MemoryError Idea is to do calculate things on fly and record the required values. 想法是即时计算事物并记录所需的值。

def comb(n, k):
        deno = 1
        num = 1
        result = 1
        #set the value of deno and num bounds
        if k > n - k:
                num_val = k + 1
                den_val = n - k
        else:
                num_val = n - k + 1
                den_val = k
        i = n
        #calculate n * (n - k) *....* (n-num_value))
        while i != num_val - 1:
                if i == 0:
                        result *= 1
                else:
                        result *= i
                if i == num_val:
                        num = result
                i -=1
        i = 0
        result = 1
        #calculate den_val! (factorial of denominator)
        while i != den_val + 1:
                if i == 0:
                        result *= 1
                else:
                        result *= i
                if i == den_val:
                        deno = result
                i += 1
        ans = num/deno
        return ans


if __name__ == "__main__":
        n = input("Enter n\n")
        k = input("Enter k\n")
        print(comb(n, k))

Complexity - O(max(k, n - k)) 复杂度-O(max(k,n-k))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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