首页 > 解决方案 > 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!

标签: pythonfunctiontuples

解决方案


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):.


推荐阅读