📌  相关文章
📜  Python程序检查所有字符串是否相互不相交

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

Python程序检查所有字符串是否相互不相交

给定一个字符串列表,我们的任务是编写一个Python程序来检查所有字符串是否彼此不相交。

例子:

方法#1:使用any() + intersection() + enumerate()

在此,我们使用intersection() 执行获取公共元素的任务,并且使用enumerate() 在字符串的所有组合之间执行交集,而any() 用于测试任何字符串是否在other 中存在任何字符字符串。

Python3
# Python3 code to demonstrate working of
# Test if all strings are mutually disjoint
# Using any() + intersection() + enumerate()
  
# initializing list
test_list = ["gfg", "is", "bet"]
  
# printing original list
print("The original list is : " + str(test_list))
  
# performing intersection of each string with every other
res = not any(set(list(sub1)).intersection(set(list(sub2)))
              for idx, sub1 in enumerate(test_list) 
              for sub2 in test_list[idx + 1:])
  
# printing result
print("Are strings mutually disjoint? : " + str(res))


Python3
# Python3 code to demonstrate working of
# Test if all strings are mutually disjoint
# Using 
  
# initializing list
test_list = ["gfg", "is", "bet"]
               
# printing original list
print("The original list is : " + str(test_list))
  
# performing concatenation and checking 
# for lengths 
concats = ''.join(test_list) 
res = len(concats) == len(set(concats))
  
# printing result
print("Are strings mutually disjoint? : " + str(res))


输出:

The original list is : ['gfg', 'is', 'bet']
Are strings mutually disjoint? : True

方法 #2:使用join() + len() + set()

这个问题可以通过匹配连接的字符串长度并检查字符串和转换集的长度是否相等来解决。在类似字符串包含重复元素的情况下失败。

蟒蛇3

# Python3 code to demonstrate working of
# Test if all strings are mutually disjoint
# Using 
  
# initializing list
test_list = ["gfg", "is", "bet"]
               
# printing original list
print("The original list is : " + str(test_list))
  
# performing concatenation and checking 
# for lengths 
concats = ''.join(test_list) 
res = len(concats) == len(set(concats))
  
# printing result
print("Are strings mutually disjoint? : " + str(res))

输出:

The original list is : ['gfg', 'is', 'bet']
Are strings mutually disjoint? : False