有没有Go语言的等价物来实现Python的itertools.combinations函数?

huangapple go评论78阅读模式
英文:

Is there a Go equivalent of Python's itertools.combinations?

问题

我正在尝试在go中找到一个集合的所有可能组合,但我只能找到使用Python的itertools库来获取所有可能的元组的解决方案。例如,如果我有原始集合['0', '1', '2'],那么可能的组合将是[['0'], ['1'], ['2'], ['0', '1'], ['0', '2'], ['1', '2'], ['0', '1', '2']]。我无法找出如何避免重复集合,比如['0', '1']和['1', '0']。谢谢!

英文:

I'm trying to find all possible combinations of a set in go, and I've only been able to find solutions for how to do this using Python's itertools to get all the tuples possible. For example, if I have the original set

['0', '1', '2'],

then the possible combinations would be

[['0'], ['1'], ['2'], ['0', '1'], ['0', '2'], ['1', '2'], ['0', '1', '2']]

I can't figure out how to do it without repeating sets, like ['0', '1'] and ['1', '0'].

Thank you!!

答案1

得分: 1

我认为这个工具可以帮助你获得所需的组合。

例如:

// 生成整数切片的组合
// 从可迭代对象中选择 r = 3 个元素的组合
r := 3
iterable := []int{1, 2, 3, 4}

for v := range CombinationsInt(iterable, r) {
      fmt.Println(v)
}

输出:

[1 2 3]
[1 2 4]
[1 3 4]
[2 3 4]
英文:

I think this tool can help you get the required combinations.

Ex:

// Generating combinations Slices of integers
// combinations of r = 3 elements chosen from iterable
r := 3
iterable := []int{1, 2, 3, 4}

for v := range CombinationsInt(iterable, r) {
      fmt.Println(v)
}

output:

[1 2 3]
[1 2 4]
[1 3 4]
[2 3 4]

huangapple
  • 本文由 发表于 2021年7月23日 14:18:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/68494822.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定