Source From Here
Question
In Python I have a list of n lists, each with a variable number of elements. How can I create a single list containing all the possible permutations:
For example
I want:
Note I don't know n in advance. I thought
itertools.product would be the right approach but it requires me to know the number of arguments in advance.
How-To
You don't need to know n in advance to use itertools.product. e.g.:
From HackerRank, this question "Maximiize it" is a good example to leverage above introduction:
Question
In Python I have a list of n lists, each with a variable number of elements. How can I create a single list containing all the possible permutations:
For example
- [ [ a, b, c], [d], [e, f] ]
- [ [a, d, e] , [a, d, f], [b, d, e], [b, d, f], [c, d, e], [c, d, f] ]
How-To
You don't need to know n in advance to use itertools.product. e.g.:
From HackerRank, this question "Maximiize it" is a good example to leverage above introduction:
- from itertools import product
- from functools import reduce
- N, M = list(map(lambda e: int(e), input().split()))
- nlist = []
- for i in range(N):
- n = list(map(lambda e: int(e), input().split()))
- nlist.append(n[1:])
- nset = set()
- max_val = 0
- for t in product(*nlist):
- val = reduce(lambda s, e: s + pow(e, 2), t, 0) % M
- if val > max_val:
- max_val =val
- print(max_val)
沒有留言:
張貼留言