檢查給定字串是否可以透過連線 Python 列表中的字串元素來形成


有時我們需要檢查是否可以從列表中存在的許多字串中形成所需的字串。列表中存在的字串的順序也不重要,這些字串需要連線起來以獲得所需的字串。

使用排列

從 itertools 中,我們可以使用 permutations 函式,它將以各種順序為我們提供列表中字串的可能組合。一旦給定的組合與所需的字串匹配,我們就得出結論,該字串可以被形成。

示例

 現場演示

from itertools import permutations

chk_str = 'balloon'
Alist = ['fly','on', 'o', 'hot', 'ball', 'air']

def findstring(strchk, biglist):
   for i in range(2, len(biglist) + 1):
      for perm in permutations(biglist, i):
         if ''.join(perm) == strchk:
         return True
   return False

# Using the function
if(findstring(chk_str,Alist)):
   print("String can be formed.")
else:
   print("String can not be formed.")

輸出

執行以上程式碼將得到以下結果:

String can be formed.

使用正則表示式

re 模組提供了 compile 函式,該函式將透過指定正則表示式模式來建立可能的字串。然後將其與要檢查的字串進行比較。如果結果不是 none,那麼我們可以得出結論,該字串可以被形成。

示例

 現場演示

import re

chk_str = 'balloon'
Alist = ['fly','on', 'o', 'hot', 'ball', 'air']

def findstring(strchk, biglist):
   r = re.compile("(?:" + "|".join(biglist) + ")*$")
   if r.match(strchk) != None:
      return True
   return False

# Using the function
if(findstring(chk_str,Alist)):
   print("String can be formed.")
else:
   print("String can not be formed.")

輸出

執行以上程式碼將得到以下結果:

String can be formed.

更新於: 2020年5月13日

498 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告