Python程式檢查所有字串是否互不相交


字串是其中一種資料結構,它儲存用雙引號或單引號括起來的資料,即任何包含在引號內的任何資料型別都被視為字串。它是不可變的,一旦我們定義了資料,就不能更改或修改。在Python中,我們有一個名為str()的函式,它接受任何資料作為輸入並返回字串作為輸出。

互不相交是指沒有兩個字串具有相同的公共元素。檢查所有字串是否互不相交的方法有很多種。讓我們逐一瞭解。

使用巢狀迴圈

巢狀迴圈是一種與迴圈相關的演算法,它在主迴圈內建立另一個迴圈。

示例

在這個例子中,我們建立了一個巢狀迴圈來檢查兩個字串中的每個元素,如果字串互不相交,則返回True,否則返回False。以下是檢查字串是否互不相交的示例。

def are_disjoint(strings):
   for i in range(len(strings)):
      for j in range(i + 1, len(strings)):
         if set(strings[i]) & set(strings[j]):
            return False
   return True
my_strings = ["Welcome", "to tutorialspoint", "Happy", "Learning"]
if are_disjoint(my_strings):
   print("All strings are mutually disjoint.")
else:
   print("Strings are not mutually disjoint.")

輸出

Strings are not mutually disjoint.

使用any()函式

在Python中,我們有一個名為any()的函式,如果可迭代物件中的任何元素為True,則返回True,否則返回False,即如果任何元素與另一個字串中的元素相同,則返回True,否則返回False。

示例

在這個例子中,我們將字串作為輸入引數傳遞給any()函式,並檢查是否有任何字串相似,然後返回True或False。

def are_disjoint(strings):
   return not any(set(strings[i]) & set(strings[j]) for i in range(len(strings)) for j in range(i + 1, len(strings)))
my_strings = ["hello", "world", "python"]
if are_disjoint(my_strings):
   print("All strings are mutually disjoint.")
else:
   print("Strings are not mutually disjoint.")

輸出

Strings are not mutually disjoint.

使用all()函式

Python中另一個可用的函式是all()函式,如果所有可迭代物件都為True,則返回True,否則返回False。

示例

在這個例子中,我們將遍歷字串,並檢查每一對字串之間是否存在任何公共字元。如果找到公共字元,則函式返回False,表示字串不互不相交。如果沒有找到公共字元,則函式返回True。

def are_disjoint(strings):
   return all(not set(strings[i]).intersection(*map(set, strings[:i] + strings[i+1:])) for i in range(len(strings)))
my_strings = ["hello", "world", "python"]
if are_disjoint(my_strings):
   print("All strings are mutually disjoint.")
else:
   print("Strings are not mutually disjoint.")

輸出

Strings are not mutually disjoint.

更新於:2023年10月19日

91 次檢視

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.