我想检查这个“a”和“b”是否在用户输入中。 例如:用户输入“hello”,它会说这不是一个ab词。 例如:如果用户输入“bag”,它会说这是一个ab词。 例如:如果用户输入“age”,它会说它不是 ab 词(因为缺少 b)。
我尝试了很多方法,其中包括使用计数器来计算字母表在字符串中出现的次数。 如果“a”和“b”在字符串内部,则打印“inside”,否则如果其中一个不在内部或两者都不在内部,则打印“not inside”
请帮帮我。我已经尝试过,但似乎无法正常工作。
def tryword(x):
if x == '':
return 0
lastNum= x[-1]
if (lastNum == "a" and "b"):
return tryword(x[:-1]) + 1
else:
return tryword(x[:-1]) + 0
if recursiveWord >= 0:
print "inside"
else:
print" not inside"
print tryword("abcdef")
最佳答案
您需要添加两个累加器参数来跟踪是否找到每个字符。每个都有一个 bool 值。
def trywordp(x, foundA, foundB):
if foundA and foundB: return True # Positive base case: Both found!
if x == "": return False # Negative base case: String exhausted
if x[0] == 'a': return trywordp(x[1:], True, foundB) # First character in string is 'a', continue checking next character
if x[0] == 'b': return trywordp(x[1:], foundA, True) # Ditto for 'b'
return trywordp(x[1:], foundA, foundB) # Neither 'a' nor 'b', continue looking
def tryword(x):
return trywordp(x, False, False) # We have not found any of them yet so start with foundA and foundB as False
if tryword("stringwithaandb"):
print "inside"
else:
print "not inside"
关于python - 检查递归中的 2 个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33011160/