Skip to main content
 首页 » 编程设计

python之在递归中检查 2 个字符

2024年10月24日14lovecherry

我想检查这个“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"