python - 如何通过使用python添加来获取目标
问题描述
我有一份清单和一个目标号码。
- 我需要打印达到目标的方式数量
l = [1,2,3]
target = 5
方式数如下
- 1+ 1 + 1 + 1 + 1 = 5
- 1 + 1 + 1+ 2 =5
- 1 + 2 + 2 = 5
- 1 +1 +3 =5
- 2 + 3 = 5
输出5
方式
def countways(l, target ):
if (target == 0):
return 0
else:
pass
if __name__ == "__main__":
l = [1,2,3],
target = 5
countways(l, target )
我们可以使用本机 python 还是itertools
?
解决方案
我将假设所有数字都是正数。
您可以使用 itertools 来检查 all combinations_with_replacement
,正如 Ann 所建议的那样,但是对于大型输入,它会变得不必要地慢,因为有很多组合。
朴素的递归方法
这个版本使用 Nevetha 描述的递归方法,它允许提前返回找不到匹配项的分支,但应该通过替换来实现。
与其他结果一样:扩展打印实际总和相当容易。我们将简单地添加一个可选的第三个参数,它给出了到目前为止的总和,并在target == 0
案例中打印它。
def countWays(elements, target):
if target < 0:
return 0
if target == 0:
return 1
total = 0
for index, element in enumerate(elements):
total += countWays(elements[index:], target - element)
return total
if __name__ == '__main__':
print(countWays([1, 2, 3], 5))
print(countWays([5, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40], 30))
print(countWays([2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37], 40))
print(countWays([1, 2, 3, 4, 5], 200))
DP算法
如您所见,对于 200 的目标,这已经需要相当长的时间来执行。这是因为在递归结束时,我们总是只将结果加一。这可以通过使用动态编程来改进——或者通过简单地添加缓存(示例代码,当然全局变量不应该在任何实际程序中使用):
cache = {}
def countWays(elements, target):
global cache
if target < 0:
return 0
if target == 0:
return 1
cache_key = (tuple(elements), target)
if cache_key in cache:
return cache[cache_key]
total = 0
for index, element in enumerate(elements):
total += countWays(elements[index:], target - element)
cache[cache_key] = total
return total
或者直接构建 dp 数组,如这里已经讨论过的:
def countWays(elements, target):
dp = [1] + [0] * target
for element in elements:
for i in range(0, target - element + 1):
dp[i + element] += dp[i]
return dp[target]
推荐阅读
- python - 使用 Docker 运行文件夹中的每个文件
- sql-server - SSRS 结果与具有相同查询和参数的 SSMS 结果不同
- vue.js - VueJS:多个单个文件组件是每个 vue 实例还是嵌套对象?
- javascript - React(Typescript ver)中导出接口Props的目的是什么
- android - 手机没有 SIM 卡,仍然 (Boolean)method.invoke(cm) 在 android 中返回 true
- php - 如何解决未找到列:基于此查询生成器的“字段列表”中的 1054 列“产品”未知?
- c# - .NET 项目中的 ToolsVersion 规范
- python - 将scrapy设置为django中的应用程序时出现“moduleNotFoundError”
- java - 如何在循环中生成 Spark 数据集聚合长专家?
- bluetooth - 经典模式下的 BT 4.2 会连接到 BT 2.1+EDR 吗?