英文:
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]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论