簡體   English   中英

function 檢查一個字符串是否包含另一個字符串的所有元素

[英]function to check if a string contains all elements of another string

我需要編寫一個 function,它接受兩個字符串 arguments,如果第二個字符串的字符存在於第一個字符串中,則返回 TRUE,否則返回 FALSE。 例如:給定str1 = 'xBxxAxxCxxAxCxxBxxxAxCxBxxxAxxBxCx'str2 = "ABC" ,返回TRUEstr2 = "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 之前定義str1str2

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)

這是另一種在functoolsoperator庫的幫助下檢查字符串是否包含另一個字符串的所有元素的方法。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM