代码之家  ›  专栏  ›  技术社区  ›  ealeon

在python中生成置换[closed]

  •  -5
  • ealeon  · 技术社区  · 7 年前

    def generate_perm(m,n):
        '''
         implement this
        '''
        return
    

    generate_perm(2,5) 应力输出

    [(1,4), (2,3), (3,2) (4,1)]
    

    generate_perm(3,5) 应输出:

    [(1,1,3), (1,2,2), (1,3,1), (2,1,2), (2,2,1), (3,1,1)]
    

    编辑 我还没走多远

    def generate_permutations(m, n):
        all = []
        cur = [0 for i in range(m)]
        len_perm = m*2
        while True:
            for i in range(m):
                if cur[i] == 0: # initial case
                    if i != m-1:
                        cur[i] = 1
                    else:
                        cur[i] = n-m
    
            all.append(cur)
            if len(all) >= len_perm:
                break
        return all
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   user2390182    7 年前

    def perm(m, n):
      if m == 1:  # base case
        return [(n,)]
      perms = []
      for s in range(1, n):  # combine possible start values: 1 through n-1 ...
        for p in perm(m-1, n-s):  # ... with all appropriate smaller perms 
          perms.append((s,) + p)
      return perms
    
    >>> perm(1, 5)
    [(5,)]
    >>> perm(2, 5)
    [(1, 4), (2, 3), (3, 2), (4, 1)]
    >>> perm(3, 5)
    [(1, 1, 3), (1, 2, 2), (1, 3, 1), (2, 1, 2), (2, 2, 1), (3, 1, 1)]
    
        2
  •  2
  •   abc    7 年前

    考虑一个列表 l = [1,2,3,4,5]

    itertools.permutations

    p = itertools.permutations(list(range(1,6)),2)
    

    my_elems = [el for el in p if sum(el) == 5]
    

    输出

    [(1, 4), (2, 3), (3, 2), (4, 1)]
    

    看看你给出的第二个例子,我想你想要的是 product ,不是 permutations

    p = itertools.product(list(range(1,6)),repeat=3)
    
    my_elems = [el for el in p if sum(el) == 5]
    
    #[(1, 1, 3), (1, 2, 2), (1, 3, 1), (2, 1, 2), (2, 2, 1), (3, 1, 1)]
    

    这对第一个案子也有效。