[英]Determining the permutation of two strings
我怎样才能找到两个字符串的排列? 例如,如果我们有:
permuted_strings('嘿','eyh')
我们应该得到的排列列表是 [1,2,0]
注意:没有理由将您的字符串放在列表中。 它们已经像列表一样,所以你可以做A[2]
,例如。
假设字符串中的所有字符都是唯一的,这很容易解决。
A = "hey"
B = "eyh"
我们可以制作一个将每个字符映射到其索引的字典:
d = {val:idx for idx, val in enumerate(A)}
现在,我们可以在每一个字符映射B
其在指数A
:
o = [d[val] for val in B]
编辑:您可以将其变成一个简单的函数,如下所示。
def get_perm_idxs(A, B):
d = {val:idx for idx, val in enumerate(A)}
return [d[val] for val in B]
此代码适用于您的简单示例。 但是,就像 Aku 的答案一样,当角色多次出现时,它需要进行一些更改。
def get_permutations_by_index(str_a, str_b):
return [str_a.index(char) for char in str_b]
def get_index_permutations(str_a, str_b):
indices = []
for char_b in str_b:
for index, char_a in enumerate(str_a):
if char_a == char_b:
indices.append(index)
break
return indices
# If you are checking large strings, you could use the dictionary based approach
# inspired by Aku's answer (his answer returns the last seen index of chars)
def get_index_permutations_by_dict(str_a, str_b):
indices = {}
for index, char in enumerate(str_a):
if char not in indices:
# if char occurs multiple times in str_a, we just want the first index
indices[char] = index
return [indices[char] for char in str_b]
get_permutations_by_index('hey', 'eyh')
>> [1, 2, 0]
get_index_permutations('hey', 'eyh')
>> [1, 2, 0]
get_index_permutations_by_dict('hey', 'eyh')
>> [1, 2, 0]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.