gpt4 book ai didi

python - Python : How do I simplify this code? 优化

转载 作者:太空宇宙 更新时间:2023-11-04 08:41:20 25 4
gpt4 key购买 nike

我是 python 的新手,我试图解决这个优化问题:

    In How many possible ways can I receive 42 emails in 7 days?

我用 Python 编写了这个程序来计算所有的解决方案:

n = 42
print(n, "emails can be received in the following ways:")
solcount = 0
for d1 in range (n+1):
for d2 in range (n+1-d1):
for d3 in range (n+1-d1-d2):
for d4 in range (n+1-d1-d2-d3):
for d5 in range (n+1-d1-d2-d3-d4):
for d6 in range (n+1-d1-d2-d3-d4-d5):
for d7 in range (n+1-d1-d2-d3-d4-d5-d6):
if d1+d2+d3+d4+d5+d6+d7 == n:
solcount +=1
print("There are", solcount, "possible solutions")

其中 d1 到 d7 分别是第 1 到 7 天收到的电子邮件数量。

现在,这有两个问题:

  1. 运行时间高得离谱,我怀疑这个算法远非最佳。
  2. 代码不允许我改变天数(就像我将天数固定为变量k)。

我该如何简化它?

谢谢!

最佳答案

正如 Rory Daulton 所指出的,这是一个 stars and bars问题。我会尽量用简单的方式解释它,所以不要费心去维基百科。

现在,假设您在 3 天内只能收到 5 封电子邮件。解决方案的总数与以下的字谜相同:

"eee|e|e" # represents 3 emails in day1, 1 in day2 and 1 in day3

字谜可以计算为符号数的阶乘除以每个符号重复次数的阶乘的乘积。在我们的简单案例中:

(5 + 3 - 1)!/(5!*(3-1)!)

请注意,我们三天只需要 2 个小节。

使用这个简单的参数,您可以轻松实现如下解决方案:

from math import factorial

def possibilities(emails, days):
return factorial(emails + days - 1)//factorial(emails)//factorial(days - 1)

这个解决方案不是很有效,因为它可以计算非常大的阶乘。您可以通过寻找一种巧妙的方法来计算此值,或使用为您提供二项式系数的库来改进它,例如 scipysympy

关于python - Python : How do I simplify this code? 优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44601998/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com