简体   繁体   English

在 Python 中按字典顺序生成排列

[英]Generating permutations in lexicographic order in Python

I am struggling with the following, is my code correct and how to test if it works?我正在努力解决以下问题,我的代码是否正确以及如何测试它是否有效?

Task: Take a string as a single input argument.任务:将字符串作为单个输入参数。 You may assume the string consists of distinct lower case letters (in alphabetical order).您可以假设字符串由不同的小写字母(按字母顺序)组成。 You may assume the input is a string of letters in alphabetical order.您可以假设输入是按字母顺序排列的一串字母。

Return a list of strings where each string represents a permutation of the input string.返回一个字符串列表,其中每个字符串代表输入字符串的一个排列。 The list of permutations must be in lexicographic order.排列列表必须按字典顺序排列。 (This is basically the ordering that dictionaries use. Order by the first letter (alphabetically), if tie then use the second letter, etc. (这基本上是字典使用的排序。按第一个字母(按字母顺序)排序,如果并列则使用第二个字母,依此类推。

  • If the string contains a single character return a list containing that string如果字符串包含单个字符,则返回包含该字符串的列表
  • Loop through all character positions of the string containing the characters to be permuted, for each character:对于每个字符,遍历包含要置换的字符的字符串的所有字符位置:
  • Form a simpler string by removing the character通过删除字符形成一个更简单的字符串
  • Generate all permutations of the simpler string recursively递归生成更简单字符串的所有排列
  • Add the removed character to the front of each permutation of the simpler word, and add the resulting permutation to a list将删除的字符添加到较简单单词的每个排列的前面,并将结果排列添加到列表中
  • Return all these newly constructed permutations返回所有这些新构造的排列

[My code] [我的代码]

def perm_gen_lex(in_string):

    if (len(in_string) <= 1):
        return(in_string)

    # List of all new combinations
    empty_list = []

    # All permutations
    final_perm = perm_gen_lex(in_string[1:])

    # Character to be removed
    remove_char = in_string(0)

    # Remaining part of string
    remaining_string = in_string[1:]

    for perm in final_perm[1:]:
        for i in range(len(in_string) + 1):
            return empty_list.append(perm[:i] + remove_char + perm[i:])

    return empty_list

Some variation on this will get you moving:一些变化会让你动起来:

from itertools import product

def combinations(string):
    return [''.join(i) for i in product(string, repeat = len(string))]

print(combinations("abc"))

See https://docs.python.org/3/library/itertools.html#itertools.producthttps://docs.python.org/3/library/itertools.html#itertools.product

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM