PY
py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# help permutations
'''
the task can be done with the function >permutations(...)< from module itertools. we have to import it.
permutstions has one required argument which is the iterable that serves the values. the second argument is a number that describes how many elements each output "portion" has. since we need to have 2 and 3 elements, we have to run the permutations in a surrounding for loop that generates the number for the combinations (2 and 3).
# this demo is without the surrounding for loop
'''
from itertools import permutations
lst = [1,3,4,2]
print(list(permutations(lst,2))) # generates 2 output elements per output tuple
# => #[(1, 3), (1, 4), (1, 2), (3, 1), (3, 4), (3, 2), (4, 1), (4, 3), (4, 2), (2, 1), (2, 3), (2, 4)]
print()
print(list(permutations(lst,3))) # generates 3 output elements per output tuple
# =>[(1, 3, 4), (1, 3, 2), (1, 4, 3), (1, 4, 2), (1, 2, 3), (1, 2, 4), (3, 1, 4), (3, 1, 2), (3, 4, 1), (3, 4, 2), (3, 2, 1), (3, 2, 4), (4, 1, 3), (4, 1, 2), (4, 3, 1), (4, 3, 2), (4, 2, 1), (4, 2, 3), (2, 1, 3), (2, 1, 4), (2, 3, 1), (2, 3, 4), (2, 4, 1), (2, 4, 3)]
'''
you can see that there are "duplications" like (1, 3) and (3, 1). during processing the result we have to take care about these cases.
the following result is:
(still including all duplicates)
only (1,3) and (1,2) meets the task requirement that the sum of the combination should also be an element of the list
(1, 3)
(1, 3) => 4
(1, 4)
Enter to Rename, Shift+Enter to Preview
OUTPUT
Run