Python 如何检测一个字符串是否同时包含另一个字符串中的所有元素?它们的出现顺序如何?
我需要检测字符串Python 如何检测一个字符串是否同时包含另一个字符串中的所有元素?它们的出现顺序如何?,python,Python,我需要检测字符串'Relim'的元素是否都在字符串'Berkelium'中,同时对于'Relim'中的每个字母,按顺序出现在字符串'Berkelium'中。例如,“Relim”在“Berkelium”中,而“Relim”的出现顺序在“Berkelium”中 我的主要想法是循环字符串'Berkelium',然后逐个检查'Berkelium'中的字符是否等于字符串'Relim'中的元素,如果是,则记录此字符的索引'Relim'。在for循环之后,检查所有元素'Relim'是否以'Berkelium'
'Relim'
的元素是否都在字符串'Berkelium'
中,同时对于'Relim'
中的每个字母,按顺序出现在字符串'Berkelium'
中。例如,“Relim”在“Berkelium”中,而“Relim”的出现顺序在“Berkelium”中
我的主要想法是循环字符串'Berkelium'
,然后逐个检查'Berkelium'
中的字符是否等于字符串'Relim'
中的元素,如果是,则记录此字符的索引'Relim'
。在for循环之后,检查所有元素'Relim'
是否以'Berkelium'
的形式出现,并且是否以升序出现。由于我循环了字符串'Berkelium'
,因此我可以确保字母的出现是有序的,但问题是'Berkelium'
中有两个'e'
,我的代码不起作用。有人知道这件事吗
string1 = 'Relim'
string2 = 'Berkelium'
index = []
for i, char1 in enumerate(string2):
for j, char2 in enumerate(string1):
if char1 == char2:
index.append(j)
if sorted(index) == index and len(index) == len(string1):
result = True
else:
result = False
正如我所理解的问题,您希望按s2的顺序查找s1中的每个字符。因此,对于s1中的每个字符,搜索s2,直到找到相同的字符或用完为止。我想这个案子不重要
def s_in_s(s1, s2):
s1 = s1.lower()
s2it = iter(s2.lower())
for c1 in s1:
for c2 in s2it:
if c2 == c1:
break
else:
return False
return True
print(s_in_s('Relim', 'Berkelium'))
在不调用.lower()
的情况下,它将按原样返回True,返回False
编辑:添加更多测试用例
for seek in ('', 'r', 'BM', 'relim', 'berkelium'):
print(s_in_s(seek, 'Berkelium')) # should all be True
print()
for seek in (' ', 'x', 'BMx', 'berkeslium'):
print(s_in_s(seek, 'Berkelium')) # should all be False
你可以试试这个:
def sub_order(string1, string2):
# get all the matches in the second string
matches = [char for char in string2.lower() if char in string1.lower()]
# record the found characters that match
found = []
# create stack of string1, to ensure which characters have been found
stack = list(string1.lower())
# Go through each character in the substring
for match in matches:
# If the stack is not empty, keep checking
if stack:
# if a character matches the character at the top of the stack
if match == stack[0]:
# append what character was found, and pop the stack
found.append(match)
stack.pop(0)
# check if the string found matches string1
if "".join(found) == string1.lower():
return True
return False
此处使用的方法:
- 从
中获取出现在string2
中的所有匹配字符李>string1
- 检查每个匹配的字符,并使用基于堆栈的方法来删除已找到的字符
- 如果找到的排序与
的排序相匹配,请返回,否则尽可能继续搜索李>string1
- 尝试了一些边缘案例,似乎有效
通过
在转换为列表后从每个字符串的末尾删除字符来匹配“向后” 倒计时“未命中”,如果您到达.pop()
的末尾,并且lst1
中没有足够的匹配项lst2
lst1 = [*'Relim'.lower()] # list conversion makes copies, the lists get wholly lst2 = [*'Berkelium'.lower()] # or partially consumed ln_lst1, cnt = len(lst1), len(lst2) while lst1 and lst2: last1 = lst1.pop() while lst2 and lst2.pop() != last1: cnt -= 1 cnt >= ln_lst1 Out[264]: True
每次您找到一个字母时,只需对其余字母的字符串的其余部分进行迭代。如果字符串1有2个e,您是否要求字符串2也有2个e?字符串1有2个
s@frozen但在for循环中,其余部分是固定的。所以我不知道如何遍历字符串的其余部分,但是在e
只检查一次c2==c1,然后断开。我希望字符串'Relim'的元素都在字符串'Berkelium'中,而'Relim'中的每个字母都按顺序出现在字符串'Berkelium'中。对(在本例中,'Relim'中的每个字符进行检查。Break只打断内部循环,然后继续外部循环。我添加了更多测试。当string1='brelm'时返回False中,如果c2==c1: