我有两个变量i,j,它们显示两个集合1和2的长度,例如len(one)= i和len(two)= j。现在,我要合并这两个集合,以使每个集合有序排列。我还需要索引Python中的每个新集合。
例如:一个包含前i个大写字母,两个包含小写字母
len(one) = i
len(two) = j
expected outputs = {'abABC...', 'aAbBC...', 'aABcC...', 'aABCb...',...}
我已经尝试了以下代码,但无法正常工作。如果有人可以帮助我,我将非常感激。
from functools import reduce
from itertools import combinations
def assign(v, p):
v[p[0]] = p[1]
return v
def interp(word1, word2, size):
return (''.join(reduce(assign, zip(comb1, word1), zip(comb2, word2)))
for comb1, comb2 in zip(combinations(range(size), len(word1)),
combinations(range(size), len(word2))))
print('\n'.join(interp("ABC", "ab", 5)))
您可以使用将两个列表之一的第一项与列表其余部分的组合递归合并的函数:
def merge(a, b):
if a and b:
for (first, *rest), other in (a, b), (b, a):
yield from ([first, *merged] for merged in merge(rest, other))
elif a or b:
yield a or b
以便:
for combination in merge(['A', 'B', 'C'], ['a', 'b']):
print(''.join(combination))
输出:
ABCab
ABabC
ABaCb
AabBC
AaBCb
AaBbC
abABC
aABCb
aABbC
aAbBC
请注意,集合在Python中是无序的,因此,如果输入是集合,则无法保留预期输出的顺序ABC
和ab
建议的输出。此处给出的示例假定您的输入和输出为列表。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句