通过连接初始列表的排列形成的唯一元素列表
list of unique elements formed by concatenating permutations of the initial lists
我想合并几个列表,每个列表都应该保留一个排列。
这是一个例子:
我想合并这些列表
[[0, 7], [2, 4], [0, 1, 7], [0, 1, 4, 7]]
我想要获得的输出是例如此列表
[2, 4, 0, 7, 1]
或者正如 Sembei Norimaki 对任务的描述:
the result must be a list of unique elements formed by concatenating permutations of the initial lists.
解决方案不是唯一的,可能并不总是有可能的解决方案
第三次幸运。这有点俗气 - 它检查源列表元素的每个排列以查看哪些是有效的:
from itertools import permutations
def check_sublist(sublist, candidate):
# a permutation of sublist must exist within the candidate list
sublist = set(sublist)
# check each len(sublist) portion of candidate
for i in range(1 + len(candidate) - len(sublist)):
if sublist == set(candidate[i : i + len(sublist)]):
return True
return False
def check_list(input_list, candidate):
for sublist in input_list:
if not check_sublist(sublist, candidate):
return False
return True
def find_candidate(input_list):
# flatten input_list and make set of unique values
values = {x for sublist in input_list for x in sublist}
for per in permutations(values):
if check_list(input_list, per):
print(per)
find_candidate([[0, 7], [2, 4], [0, 1, 7], [0, 1, 4, 7]])
# (0, 7, 1, 4, 2)
# (1, 0, 7, 4, 2)
# (1, 7, 0, 4, 2)
# (2, 4, 0, 7, 1)
# (2, 4, 1, 0, 7)
# (2, 4, 1, 7, 0)
# (2, 4, 7, 0, 1)
# (7, 0, 1, 4, 2)
你肯定会更好地应用图论知识并使用图形库,但这超出了我目前的驾驶室!
我想合并几个列表,每个列表都应该保留一个排列。
这是一个例子:
我想合并这些列表
[[0, 7], [2, 4], [0, 1, 7], [0, 1, 4, 7]]
我想要获得的输出是例如此列表
[2, 4, 0, 7, 1]
或者正如 Sembei Norimaki 对任务的描述:
the result must be a list of unique elements formed by concatenating permutations of the initial lists.
解决方案不是唯一的,可能并不总是有可能的解决方案
第三次幸运。这有点俗气 - 它检查源列表元素的每个排列以查看哪些是有效的:
from itertools import permutations
def check_sublist(sublist, candidate):
# a permutation of sublist must exist within the candidate list
sublist = set(sublist)
# check each len(sublist) portion of candidate
for i in range(1 + len(candidate) - len(sublist)):
if sublist == set(candidate[i : i + len(sublist)]):
return True
return False
def check_list(input_list, candidate):
for sublist in input_list:
if not check_sublist(sublist, candidate):
return False
return True
def find_candidate(input_list):
# flatten input_list and make set of unique values
values = {x for sublist in input_list for x in sublist}
for per in permutations(values):
if check_list(input_list, per):
print(per)
find_candidate([[0, 7], [2, 4], [0, 1, 7], [0, 1, 4, 7]])
# (0, 7, 1, 4, 2)
# (1, 0, 7, 4, 2)
# (1, 7, 0, 4, 2)
# (2, 4, 0, 7, 1)
# (2, 4, 1, 0, 7)
# (2, 4, 1, 7, 0)
# (2, 4, 7, 0, 1)
# (7, 0, 1, 4, 2)
你肯定会更好地应用图论知识并使用图形库,但这超出了我目前的驾驶室!