python - Resolve TypeError "can only concatenate tuple (not 'int') to tuple" with function designed to return all summation compositions
问题描述
I'm trying to write a function in Python that returns a set of k-sized tuples that sum to n, and I'm fairly certain that I have the function written correctly, but I keep getting the type error that I mentioned in the title.
For example, compositions(3,4) should return the following: {(1, 1, 2), (1, 2, 1), (2, 1, 1)}
def compositions(k, n):
if k == 1:
return (n,)
comp = []
for SumIterator in range(1, n+1):
for FunctionRecall in compositions(k = k-1, n = n-SumIterator):
comp.append((SumIterator,) + FunctionRecall)
return set(comp)
Any idea on how to fix this function so that it runs correctly?
Thanks!
解决方案
If your function is supposed to return a set of tuples, you'll need to revise your base case.
if k == 1:
return (n,)
This doesn't return a set of tuples. It returns one tuple. Try putting it in a set.
if k == 1:
return {(n,)}
Additionally, if you don't want any of the tuples to contain zero, I think you need to change the bounds of your first for loop to for SumIterator in range(1, n):
.
推荐阅读
- reactjs - Axios 承诺解决飞行前请求响应,这使得关联的 GET 与应用程序的其余部分无序执行
- master-detail - 在 Android Studio 的 Master Detail Flow 项目中,如何在旋转手机时保存 ItemDetailActivity 的标题?
- javascript - iframe 中的 http 请求 - 缺少引荐来源网址
- masstransit - MassTransit 的重试行为是否会阻止消费其他消息?
- ms-access - Access 使用子表单一次添加多个记录
- peoplesoft - CreateRecord 更新方法不更新表
- r - 如何使用值作为列名传播数据框并填充 R 中相同单元格的计数?
- mysql - 选择十六进制(md5(“任何东西”))%4;为什么这总是零?
- datetime - 有没有办法在日期时间参考表中查找日期时间并返回相应的数据
- c - 使用表单数据时看不到 C 中上传的文件