2020年4月23日 星期四

[ Python 常見問題 ] All possible permutations of a set of lists in Python

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
  1. [ [ a, b, c], [d], [e, f] ]  
I want:
  1. [ [a, d, e] , [a, d, f], [b, d, e], [b, d, f], [c, d, e], [c, d, f] ]  
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.:
>>> import itertools
>>> s=[ [ 'a', 'b', 'c'], ['d'], ['e', 'f'] ]
>>> list(itertools.product(*s))
[('a', 'd', 'e'), ('a', 'd', 'f'), ('b', 'd', 'e'), ('b', 'd', 'f'), ('c', 'd', 'e'), ('c', 'd', 'f')]

From HackerRank, this question "Maximiize it" is a good example to leverage above introduction:
  1. from itertools import product  
  2. from functools import reduce  
  3.   
  4. N, M = list(map(lambda e: int(e), input().split()))  
  5. nlist = []  
  6. for i in range(N):  
  7.     n = list(map(lambda e: int(e), input().split()))  
  8.     nlist.append(n[1:])  
  9.   
  10. nset = set()  
  11. max_val = 0  
  12. for t in product(*nlist):  
  13.     val = reduce(lambda s, e: s + pow(e, 2), t, 0) % M  
  14.     if val > max_val:  
  15.         max_val =val  
  16.   
  17. print(max_val)  


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...