- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我想从整数列表 [3,5,7,9]
中生成所有排列,从而产生特定的总和值 15
。我实现了这个,没问题。
def add_next(seq, count, m):
s = sum(seq)
if s == m:
count += 1
print(seq)
elif s < m:
for i in [3,5,7,9]:
add_next(seq + [i], count, m)
else:
return count
add_next([], 0, 15)
输出:
[3, 3, 3, 3, 3]
[3, 3, 9]
[3, 5, 7]
[3, 7, 5]
[3, 9, 3]
[5, 3, 7]
[5, 5, 5]
[5, 7, 3]
[7, 3, 5]
[7, 5, 3]
[9, 3, 3]
问题是如何重写此函数以仅返回可能的排列数作为函数结果?因为对于巨大的列表和大的总和值,生成所有字符串输出是不合理的。我不完全理解如何在递归函数内部和外部传递值。
我试过:
def add_next2(seq, count, m):
s = sum(seq)
if s == m:
count += 1
print(seq)
elif s < m:
for i in [3,5,7,9]:
count = add_next2(seq + [i], count, m)
else:
return count
add_next([], 0, 15)
但它返回错误 TypeError: unsupported operand type(s) for +=: 'NoneType' and 'int'
。所以 count
是 None
。为什么?
另一种选择是如何重写此函数以将其转换为生成器并依次产生输出字符串?
最佳答案
如果您只是计算成功的递归结果,则不需要“计数”作为参数。可以只返回成功的结果为1,不成功的结果为0,让它们累加。
EDIT 2 更简洁但仍可读
def add_next(seq, m):
s = sum(seq)
count = 1 if s == m else 0
if s < m:
for i in [f for f in [3,5,7,9] if s + f <= m]:
count += add_next(seq + [i], m)
return count
print(add_next([], 15))
编辑您还可以过滤 [3,5,7,9] 列表,以便您的 for i in 循环仅处理有可能成功的元素。
for i in [f for f in [3,5,7,9] if s + f <= m]:
关于python - 整数的所有排列对应于特定的和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20103849/
我想检查我的应用程序或系统中是否存在库。在 Java 中,我通常执行 System.loadlibrary,但是有谁知道 C 中类似的相应调用吗? 最佳答案 是dlopen打开一个库,dlsym 从加
我在 typescript 中输入以下内容 export type Excludable = T & { isExcluded?: boolean } 其中过滤值: export type Filte
我最近在我的应用程序中添加了一种方法,可以自动格式化 TextView ,从“50000”到“50,000”,效果绝对完美。现在我遇到的问题是,在我的应用程序中,有多个按钮功能可以从该 TextVie
SELECT * FROM conversations WHERE chatMembers LIKE '%1%'AND chatMembers LIKE '%10%' 对话表 id | chatMem
我正在编写一个需要将 Java Date() 值保存到 MySQL 数据库的 RESTful Web 服务,但是,我不确定 MySQL 中可以保存 Java Date() 的数据类型是什么,或者我是否
同样,在任何 Red Hat 或 JBoss 站点上都没有关于此的信息,所以我在这里问... 我不确定是 13 还是 14。 最佳答案 Mapping the Community versions w
同样,在任何 Red Hat 或 JBoss 站点上都没有关于此的信息,所以我在这里问... 我不确定是 13 还是 14。 最佳答案 Mapping the Community versions w
我曾尝试使用 swift 开发一款利用 iPhone 的 3D 触摸硬件的游戏。然而,当我将我的应用程序提交到 App Store 时,它被拒绝了,因为该游戏无法在 iPad 上玩。 我的问题是,
Qt 的有序关联容器对应项 std::map是QMap , std::set是QSet , 对于无序关联容器 std::unordered_map是QHash . 我应该用什么来代替std::unor
JavaScript 方法 String.fromCharCode() 在以下意义上与 Python 的 unichar() 等效: print unichr(213) # prints Õ on t
正如谷歌在 "Discontinuing support for JSON-RPC and Global HTTP Batch Endpoints" 中提到的那样,Google API 客户端库已重新
我正在使用 MapLayer 和 MapOverlay 在 map 中创建自己的路径/折线,GPS 捕获的所有点都存储在一个结构中,以便我可以访问它们。随时。 现在,我希望路径在用户操作 map (缩
我们使用 Adobe Flash Builder 创建由 Flex 提供支持的交互式 Web 应用程序。现在我们正在寻找替代方案,让我们在 UI 设计和迎合 HTML5 的编码方面拥有同样的开发便
我想知道Android/Java 中类似C#/C++ 中的GetTickCount 方法的相应方法吗? 最佳答案 Android 为 SystemClock.uptimeMillis() .请注意,u
我用 Vue + Phaser 开始了新项目,但是当我尝试加载 Assets 时,this.game.load.image 中的“load”和“add”返回“undefined”。我尝试从 JS 文件
我是一名优秀的程序员,十分优秀!