Translating python function to go function

Viewed 25

I am trying to translate this Python function to Go:

def linear_compositions(n, k):
    if n < 0 or k < 0:
        return
    elif k == 0:  
        if n == 0:
            yield []
        return
    elif k == 1:
        yield [n]
        return
    else:
        for i in range(1, n):
            for comp in linear_compositions(n - i, k - 1):
                yield [i] + comp

This is what I came up with so far, but I cannot translate the yield in the last else block:

func linearComposition(n, k int) [][]int {
    var result [][]int
    if n < 0 || k < 0 {
        return nil
    } else if k == 0 {
        if n == 0 {
            return result
        }
    } else if k == 1 {
        return [][]int{{n}}
    } else {
        for i := 1; i < n; i++ {
            for _, comp := range linearComposition(n-1, k-1) {
                result = append(result, comp)
            }
        }
    }
    return result
}

At the moment, with inputs n=12 and k=5 it returns a large amount of slices of slices with 8 in index 0.

I have followed this post to help me with the translation and understanding of the Python yield keyword.

0 Answers
Related