[英]Finding occurence of one word in the second using string methods
所以我有一个函数,它接受两个只有字母的单词,如果第二个单词出现在第一个单词中的顺序与单词中的顺序完全相同,则返回 True 。
例如,如果我有:
>>> within('builder','bild')
它将返回 True 作为 bild,出现在第一个单词中,与第二个单词中的顺序相同。
虚假陈述的一个例子是:
>>> within('builder', 'bidl')
因为即使 word2 中的字母在 word1 中,它们的顺序也不同。
我试图做的是使用 for 循环和范围来获取单词 2 中每个字母第一次出现在单词 1 中的索引,但在这种情况下它不起作用:
>>> within('aaaacadgt', 'cat')
因为 a 的索引会给我第一个索引并导致返回值为 False,即使它是 True。
请注意,除了字符串之外,我不能使用任何方法。
所以没有列表、字典、元组等。
使用正则表达式有一种有趣的方法来处理这个问题:
import re
def within(big, small):
# we will do this with a regular expression, checking for each character in order,
# with any number of any kind of character in between them, and before/after
# '.*' will get this.
rexp = '.*' + '.*'.join(re.escape(small)) + '.*'
# then, we just see if the regex matches
return (re.match(rexp, big) is not None)
也就是说,也可以不用正则表达式。 考虑递归方法:
def within(big, small):
# base case: return True on an empty string
if small == '':
return True
# Find the first occurrence in `big` of the first character
try:
idx = big.index(small[0])
# If it's there, then search for the next character, after that point
# by using string slicing
return within(big[(idx + 1):], small[1:])
except Indexerror:
# If the first character of small is not in big, then small can't occur in big.
return False
通过以某种方式跟踪索引,这可以推广为非递归方法。 它与您正在执行的操作类似 - 但它会切断字符串的前端以避免出现错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.