python代码太长_python-此代码效率太低,如何增加内存和执行...

首先,组合是可迭代的.这意味着您无需遍历它们就可以将它们转换为列表.实际上,这样做的效率极低.

下一个可以明显改善的是您的因素程序.目前它是线性的.我们可以做得更好.我们可以通过以下算法获得整数N的因数:

>得到N的素因式分解,使得N = p1 ^ n1 * p2 ^ n2 * …

> N的因数为(1 n1)*(1 n2)* …

另外,您当前的解决方案还有很多未使用的变量和计算.摆脱它们.

有了这些,我们得到以下应该起作用的内容:

from functools import reduce

from operator import mul

from itertools import combinations

# Starting from the maximum, we can divide our bag combinations to see the total number of integer factors

def prime_factors(n):

p = 2

dct = {}

while n != 1:

if n % p:

p += 1

else:

dct[p] = dct.get(p, 0) + 1

n = n//p

return dct

def number_of_factors(n):

return reduce(mul, (i+1 for i in prime_factors(n).values()), 1)

def kinderLevon(bags):

candies = list()

for x in (combinations(bags, i) for i in range(1, len(bags)+1)):

for j in x:

candies.append(sum(j))

satisfied_kids = [number_of_factors(i) for i in candies]

return candies[satisfied_kids.index(max(satisfied_kids))]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值