[英]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. (这基本上是字典使用的排序。按第一个字母(按字母顺序)排序,如果并列则使用第二个字母,依此类推。
[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.product见https://docs.python.org/3/library/itertools.html#itertools.product
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.