📜  Python – 跨列表的不相交字符串

📅  最后修改于: 2022-05-13 01:55:10.337000             🧑  作者: Mango

Python – 跨列表的不相交字符串

给定两个列表,提取所有不相交的字符串对,即没有任何共同字符的字符串对。

方法:使用set() + yield [ generator ] + reduce() +递归

在这里,我们使用 set & operation 执行获取不相交字符串的任务,并使用 yield 动态提取。使用递归检查每个后续字符串是否不相交。

Python3
# Python3 code to demonstrate working of
# Disjoint Strings across Lists
# Using set() + yield [ generator ] + reduce() + recursion
from functools import reduce
  
# helper function
def dis_pairs(dpair, res=[]):
  
    # checking for disjoint pair
    if not dpair and not reduce(lambda a, b: set(a) & set(b), res):
        yield tuple(res)
  
    # recurring for subsequent pairs
    elif dpair:
        yield from [idx for k in dpair[0] for idx in dis_pairs(dpair[1:], res + [k])]
  
  
# initializing lists
test_list1 = ["haritha", "is", "best"]
test_list2 = ["she", "loves", "papaya"]
  
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
  
# calling function
res = list(dis_pairs([test_list1, test_list2]))
  
# printing result
print("All possible Disjoint pairs : " + str(res))


输出: