檢查給定字串是否可以透過連線 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.
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP