【问题标题】:Odered permutations in python [duplicate]python中的有序排列[重复]
【发布时间】:2020-04-14 04:56:21
【问题描述】:

您好,我尝试使用字符串参数创建函数并返回有序排列字典。 示例:

单词 = 'abc'; func(word) - > [a, b, c, ab, ac, bc, abc]

【问题讨论】:

标签: python permutation


【解决方案1】:

itertools.combinations 按字典顺序返回

有点像

def word(w):
   for i in range(len(w)):
      yield from itertools.combinations(w,i+1)

编辑:

这和 powerset 一样是错误的,因为它不会按字典顺序返回所有结果。

【讨论】:

    【解决方案2】:

    我认为您指的是组合。 排列是元素中不同顺序很重要的组合。 如果 'ab' 的组合看起来像 ['a', 'b', 'ab'],则排列看起来像 ['a', 'b', 'ab', 'ba']

    from itertools import combinations
    
    word = 'abc'
    my_list = []
    for n in range(len(word)):
        my_list.extend([''.join(x) for x in combinations(word, n + 1)])
    
    print(my_list)
    

    结果:

    ['a', 'b', 'c', 'ab', 'ac', 'bc', 'abc']
    

    【讨论】:

      【解决方案3】:

      def toString(List): return ''.join(List)

      def permute(a, l, r): 
      if l==r: 
          print toString(a) 
      else: 
          for i in xrange(l,r+1): 
              a[l], a[i] = a[i], a[l] 
              permute(a, l+1, r) 
              a[l], a[i] = a[i], a[l]
      string = "ABC"
          n = len(string) 
          a = list(string) 
          permute(a, 0, n-1) 
      

      【讨论】:

        猜你喜欢
        • 2017-04-28
        • 2019-11-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-26
        • 2017-02-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多