1 | initial version |
Python's itertools module has lots of useful functions, including:
sage: import itertools
sage: ListA = [1,2,3]
sage: S = itertools.combinations_with_replacement(ListA, 2)
sage: list(S)
[(1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)]
2 | No.2 Revision |
Python's itertools module has lots of useful functions, including:
sage: import itertools
sage: ListA = [1,2,3]
sage: S = itertools.combinations_with_replacement(ListA, 2)
sage: list(S)
[(1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)]
Edit: If you want to use Sage-specific code, you can use [Combinations]. (https://doc.sagemath.org/html/en/reference/combinat/sage/combinat/combination.html#sage.combinat.combination.Combinations) This will return duplicates only if they appear in the original list, so you can use ListA * n
to get n
copies of your list, and then choose combinations from that:
sage: S = Combinations(ListA * 2, 2)
sage: list(S)
[[1, 1], [1, 2], [1, 3], [2, 2], [2, 3], [3, 3]]
The itertools
versions seem to be faster, in my limited testing.
3 | No.3 Revision |
Python's itertools module has lots of useful functions, including:
sage: import itertools
sage: ListA = [1,2,3]
sage: S = itertools.combinations_with_replacement(ListA, 2)
sage: list(S)
[(1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)]
Edit: If you want to use Sage-specific code, you can use [Combinations]. (https://doc.sagemath.org/html/en/reference/combinat/sage/combinat/combination.html#sage.combinat.combination.Combinations) Combinations. This will return duplicates only if they appear in the original list, so you can use ListA * n
to get n
copies of your list, and then choose combinations from that:
sage: S = Combinations(ListA * 2, 2)
sage: list(S)
[[1, 1], [1, 2], [1, 3], [2, 2], [2, 3], [3, 3]]
The itertools
versions seem to be faster, in my limited testing.