[英]Finding all possible permutations with 3 Constants
since im sure youre all aware of the "Real Donut Shop Problem" ( https://math.stackexchange.com/questions/223345/counting-donuts ). 因为我确信您都知道“真正的甜甜圈店问题”( https://math.stackexchange.com/questions/223345/counting-donuts )。 So i just start..
所以我才开始。
I have 3 Integers, all three are entered by a user. 我有3个整数,所有三个都是由用户输入的。 with them i need to calculate how many possible permutations they are.
和他们一起,我需要计算它们有多少种可能的排列。 I already got some code, it works fine for small integers, if they get bigger, my tool runs for literally days/hours?
我已经有了一些代码,它对于小整数可以正常工作,如果它们变得更大,我的工具实际上可以运行数天/小时?
recursive function to calculate possible permutations: 递归函数来计算可能的排列:
def T(n, k, K):
if k==0: return n==0
return sum(T(n-i, k-1, K) for i in xrange(0, K[k-1]+1))
Explanation: 说明:
K is different for each crate, and doesnt need to be full, it can even be empty. 每个板条箱的K都不相同,不需要填满,甚至可以为空。
So, as you see, im calculating how many possibilies they are, to fit X given Bottles inside X given Crates, where one crate can fit a maximum of X Bottles. 因此,如您所见,我正在计算它们的数量,以在给定X个板条箱中容纳X个给定的瓶中,其中一个板条箱最多可以容纳X个瓶。
Example for better Understanding: Lets say, we have: 更好理解的示例:可以说,我们有:
So they are 2 possibilities to fit the bottles inside the crates. 因此,有两种将瓶子装到板条箱中的可能性。
Another one: 另一个:
6 possibilities 6种可能性
Above code calculates that flawless, but when i try it with like: 上面的代码计算出完美无瑕,但是当我尝试使用它时:
Problem: 问题:
It takes FOREVER, so im asking you; 它需要永远,所以我问你;
Question: 题:
how could i improve above code/function? 我该如何改善上述代码/功能?
Your problem is exponential blowup of the number of calculations made. 您的问题是所进行的计算数量呈指数级增长。 But these calculations are calculating the same thing over and over again.
但是这些计算一遍又一遍地计算同一件事。
The solution is to store the intermediate values AKA memoization. 解决方案是存储中间值AKA备注。
Here's a version in python 3.2 using functools.lru_cache to do the memoization for you 这是python 3.2中的一个版本,使用functools.lru_cache为您做备忘录
import functools
def T(n, k, K):
@functools.lru_cache(maxsize=None)
def Tsub(n,k):
if k==0: return n==0
return sum(Tsub(n-i,k-1) for i in range(0, K[k-1]+1))
return Tsub(n,k)
print( T(7,2,[3,5]) )
print( T(7,3,[2,3,4]) )
print( T(30,20,list(range(20))) )
On my machine the final result is 2172723680407 and is obtained immediately. 在我的计算机上,最终结果为2172723680407,并立即获得。
If you don't have python 3.2 you can do it like this: 如果您没有python 3.2,可以这样做:
def T(n, k, K):
cache = {}
def Tsub(n,k):
key = (n,k)
if key in cache:
return cache[key]
if k==0:
cache[key] = (n==0)
return n==0
v = sum(Tsub(n-i,k-1) for i in xrange(0, K[k-1]+1))
cache[key] = v
return v
return Tsub(n,k)
print( T(7,2,[3,5]) )
print( T(7,3,[2,3,4]) )
print( T(30,20,list(range(20))) )
The strange nesting of functions is used to get around the issue that you can't store a list ( K
) as a key to a table. 函数的奇怪嵌套用于解决无法将列表(
K
)存储为表键的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.