都說(shuō)現(xiàn)在中國(guó)的ai也發(fā)展的怎么怎么好,于是我就測(cè)試了一個(gè)很小的問(wèn)題:用python程序?qū)崿F(xiàn)有2個(gè)字符串a(chǎn),b,如果a字符串里有至少連續(xù)3個(gè)字符串與b一個(gè)字符串里的相同,則是真,a,b字符串長(zhǎng)度都都不確定
用文心一言得出的代碼如下:
def has_consecutive_triplets_with_other_string(s1, s2): # 獲取s2中所有可能的子字符串 substrings = [s2[i:j] for i in range(len(s2)) for j in range(i + 1, len(s2) + 1)] # 遍歷s2的所有子字符串 for substring in substrings: # 使用正則表達(dá)式查找s1中連續(xù)三個(gè)相同的子字符串 pattern = rf"({re.escape(substring)}){{{3,}}}" if re.search(pattern, s1): return True # 如果沒(méi)有找到符合條件的子字符串,返回False return False # 示例 s1 = "hellohellohelloabcabc" s2 = "abc" s3 = "xyz" print(has_consecutive_triplets_with_other_string(s1, s2)) # 輸出: True print(has_consecutive_triplets_with_other_string(s1, s3)) # 輸出: False
看它一陣操作猛如虎,還有輸出,結(jié)果卻運(yùn)行不了,自己加了import re還是不行,看代碼,你說(shuō)你都遍歷了,直接判斷不就行了,為什么要使用正則?算了試試智普清言:
def contains_substring(a, b):
# 遍歷字符串b中的每個(gè)字符
for char_b in b:
# 檢查char_b在a中是否連續(xù)出現(xiàn)至少3次
if char_b * 3 in a:
return True
return False
測(cè)試函數(shù)
test_a = "abcdeeeffg"
test_b = "ef"
contains_substring(test_a, test_b)
直接都沒(méi)明白意思,直接給個(gè)白眼。
下面還是請(qǐng)我們真正的AI,CHATGPT:
def has_common_substring(a, b):
# Check for any common substring of length 3 or more
for i in range(len(a) - 2):
# Extract 3 consecutive characters from string 'a'
substring = a[i:i+3]
# Check if these 3 characters are in string 'b'
if substring in b:
return True
return False
# Example usage:
a = 'abc123'
b = '9abc456'
result = has_common_substring(a, b)
print(result) # Output would be True if there is a common substring of length 3 or more
完美,只要改你的字符串就行了,最后文心一言的只要稍微改下也可以用,自己試試吧?
未經(jīng)允許不得轉(zhuǎn)載:445IT之家 » python程序?qū)崿F(xiàn):a字符串里是否有至少連續(xù)3個(gè)字符串與b一個(gè)字符串里的相同