现在我正在尝试使用带有两个参数的函数的递归来查找第二个参数是否包含在第一个函数中。举个例子:
def recurseString(full, inclusive):
...............
有了这个,我会采取以下方式:
recurseString('jack','kcj')
这将返回“True”,而类似于:
recurseString('stan','xun')
会返回“False”
我对python很新,所以这很混乱。关于如何解决这个问题的任何想法?
答案 0 :(得分:2)
我猜你正在寻找......
In [51]: def recurseString(a,b):
....: if b == '': return True
....: else:
....: if len(b) == 1: return b in a
....: else: return (b[0] in a) and recurseString(a, b[1:])
....:
In [52]: recurseString('jack', 'kjc')
Out[52]: True
In [53]: recurseString('stan', 'xun')
Out[53]: False
但是,不需要递归。使用all
可以更好地解决这个问题:
In [57]: all( [s in 'jack' for s in 'kjc'] )
Out[57]: True
更像是Pythonic。
也可以使用更多功能的reduce
但可读性更低,因为Python有更好的方法来处理它。
In [60]: reduce(lambda x,y: (x and (y in 'jack')) , 'kjc', True)
Out[60]: True
最后,如果不使用set
表示法,这将是不完整的:
In [65]: (set('kjc') - set('jack')) == set()
Out[65]: True
正如您所看到的,递归版本最不适合此问题!
答案 1 :(得分:0)
要以递归方式思考任何问题,您必须将其分解为基本案例(或者有时是多个基本案例),以及递归案例(或者有时是多个递归案例)。
我将假设"包括在"表示inclusive
中的每个字符也位于full
中,实际上inclusive
次出现的每个字符N次也在full
中至少N次&# 34。
所以,如果inclusive
为空,那么它就是真的。
但如果full
为空且inclusive
不为空,则表示错误。
否则,如果full
的第一个字符包含在内,则iff full[1:]
包含inclusive
减去该字符时,该字符为真。
否则,如果full[1:]
包含inclusive
,则为真。
现在你只需将其翻译成代码。
如果您不需要处理重复的字符,则只需测试inclusive[0]
并在inclusive[1:]
上递归,而不是在full[1:]
上进行递归,即可简化此操作。
答案 2 :(得分:0)
def recurseString(str1,str2):
if str2 == "": # str2 == "" all str2 letters are in str1
return True
elif str2[0] in str1:
return recurseString(str1, str2[1:]) # move to next letter in str2
return False # if we get here we have found a letter that is not in str1
In [22]: recurseString('stan','xun')
Out[22]: False
In [23]: recurseString('jack','kcj')
Out[23]: True
答案 3 :(得分:0)
我不知道为什么你需要递归来实现它,它很难阅读和理解。
我的上帝,阅读我的代码对我来说是一个挑战。
def recurseSring(full, inclusive):
for i in range(len(full)):
for j in range(len(inclusive)):
if full[i] == inclusive[j]:
if recurseSring(full[i + 1:], inclusive[j + 1:]):
return True
if full[i] == inclusive[j] and len(inclusive) == 1:
return True
return False
if __name__ == "__main__":
if recurseSring('lifenglifeng001', 'lifeng'):
print('OK, equal')
else:
print('NOT equal')
答案 4 :(得分:0)
短暂而甜蜜。
def recurseString(full, incl):
return incl[:1] in full and (incl[:1] == '' or recurseString(full, incl[1:]))
'和'确保表达式的两个部分都为真。
第一部分 - 采用包含的第一个字符,并在完整字符串中搜索它:
incl[:1] in full #returns '' if incl is ''
第二部分 - 如果你使用空字符串(incl)搜索,如果递归调用是真的,并且使用incl的尾部作为第二个arg,那么它已经到了包含OR的结尾:
incl[:1] == '' or recurseString(full, incl[1:])
#null check is first to prevent overflow
答案 5 :(得分:0)
即使inclusive
中有重复的字母,但full
只有一个字母,这将返回True:
def recurseString(full, inclusive):
if not inclusive:
return True
return inclusive[0] in full and recurseString(full, inclusive[1:])
>>> print recurseString('jack','kkkcccjjj')
True
以下要求full
包含相同数量的重复的字母 - 如果inclusive
有三个k' s full
必须有三个k&# 39,S:
def recurseString(full, inclusive, first_call = True):
# first time through, sort the arguments to make the algorithm easier
if first_call:
full, inclusive = map(sorted, (full, inclusive))
first_call = False
# two base cases, inclusive has been exhausted
if not inclusive:
return True
try:
index = full.index(inclusive[0])
except ValueError:
# and (2nd base case) first item of inclusive is not in full
return False
return recurseString(full[index+1:], inclusive[1:], first_call)
>>> print recurseString('jack','kkkcccjjj')
False
>>> print recurseString('jckackjkjc','kkkcccjjj')
True
>>>
使用index
方法似乎作弊 -
def foo(full, inclusive, first_call = True):
if first_call:
full, inclusive = map(sorted, (full, inclusive))
if not full and inclusive:
return False
if not inclusive:
return True
if inclusive[0] == full[0]:
inclusive = inclusive[1:]
return foo(full[1:], inclusive, False)
assert not foo('','kkkcccjjj')
assert not foo('sun','xun')
assert not foo('jack','kkkcccjjj')
assert foo('s', 's')
assert foo('jckackjkjc','kkkcccjjj')
assert foo('','')
assert foo('a','')
答案 6 :(得分:-1)
这个没有递归的简单方法:用你想要的字符串创建两个集合,并检查一个集合是否在另一个集合中。
def contains(text, chars):
textset = set(text)
charset = set(chars)
return charset.issubset(textset)
print contains("jackie", "ice") # True
print contains('jack','kcj') # True
print contains('stan','xun') # False