0

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.

Enrico
  • 13
  • 3
  • We generally [don't do](https://meta.stackoverflow.com/questions/265825) code translation question here - all I can really do is point you back at the reference, because there is not a specific, identifiable question - "Any one can help checking this out?" [does not qualify](https://meta.stackoverflow.com/questions/284236). Think carefully about what the code needs to do and what the result should be. If Golang has equivalent functionality for generators (I've never used Golang), then use that. Otherwise, *first write Python code that works and is tested in the way you want*, then translate. – Karl Knechtel Sep 15 '22 at 11:07
  • If you need help later, focus on the Golang code, and ask a `go` question - using **English** to explain what the code needs to do and how that's different from the current behaviour, not Python. – Karl Knechtel Sep 15 '22 at 11:08

0 Answers0