I need a list of all possible combinations of k out of n numbers for very large n. I run into the problem of my list size exceeding 500000 quickly, which python does not seem to handle very well. 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
. 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))
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.