我需要检测字符串'Relim'的元素是否都在字符串'Berkelium'中,同时'Relim'中的每个字母按顺序出现在字符串'Berkelium'中。例如,“'Berkelium‘”中的“Relim”,而“Relim”的出现在'Berkelium'.中排列顺序。
我的主要想法是遍历字符串'Berkelium',然后逐个检查'Berkelium'中的字符是否等于string '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发布于 2017-11-25 00:51:48
就我所理解的问题而言,您希望在s1中按照s2中的顺序查找每个字符。因此,对于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'))这将返回True原样,在没有.lower()调用的情况下返回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发布于 2017-11-25 02:29:07
你可以试试这个:
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排序相匹配的排序,则返回,否则继续搜索(如果可能)。发布于 2017-11-25 03:44:40
试过几个边缘案件,似乎很管用
在转换为列表后,通过.pop()ing chars从每个字符串的末尾匹配“向后”
数一数“错过”,如果你到了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]: Truehttps://stackoverflow.com/questions/47481607
复制相似问题