[英]function to check if a string contains all elements of another string
我需要編寫一個 function,它接受兩個字符串 arguments,如果第二個字符串的字符存在於第一個字符串中,則返回 TRUE,否則返回 FALSE。 例如:給定str1 = 'xBxxAxxCxxAxCxxBxxxAxCxBxxxAxxBxCx'
和str2 = "ABC"
,返回TRUE
( str2 = "ABCD"
,返回FALSE
)。
我嘗試了不同的代碼變體,但無法獲得正確的代碼。 我在這里有以下代碼,我in
內置 function 中使用,但它似乎不起作用:
def minSubStr(str1, str2):
str1 = input("Enter the first string: ")
str2 = input("Enter the second string to check if the characters exist in the first string: ")
if str2 in str1:
return True
else:
return False
minSubStr(str1, str2)
str2 in str1
檢查整個字符串str2
是否作為 substring 存在於str1
中。 您需要使用all()
function 遍歷str2
以檢查str2
的每個字符是否存在於str1
中。
def minSubStr(str1, str2):
str1 = input("Enter the first string: ")
str2 = input("Enter the second string to check if the characters exist in the first string: ")
if all(s in str1 for s in str2):
return True
return False
一個非常簡潔的解決方案是在兩個字符串中的字符之間設置差異。 如果滿足您的條件,則設置的差異將為空:
return len(set(str2)-set(str1))==0
試試這個,你需要在調用 function 之前定義str1
和str2
def minSubStr(str1, str2):
if str2 in str1:
print(True)
else:
print(False)
str1 = input("Enter the first string: ")
str2 = input("Enter the second string to check if the characters exist in the first string: ")
minSubStr(str1, str2)
那么您可以使用 python 中的集合來優化迭代。
def minSubStr(str1, str2):
str1 = set(input("Enter the first string: "))
str2 = set(input("Enter the second string to check if the characters exist in the first string: "))
if all(s in str1 for s in str2)::
return True
else:
return False
minSubStr(str1, str2)
我認為您可能需要遍歷字符,例如:
for i in str1:
if str2 in str1:
return True
else:
return False
minSubStr(str1, str2)
這是另一種在functools
和operator
庫的幫助下檢查字符串是否包含另一個字符串的所有元素的方法。
from functools import reduce
from operator import and_, or_, contains
def containsAll(str1, str2):
return reduce(and_, map(contains, len(str2)*[str1], str2))
str1 = input("Enter the first string:")
str2 = input("Enter the second string to check if all characters exist:")
containsAll(str1,str2)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.