检查递归中的2个字符

2024-06-28 10:48:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我想检查这个“a”和“b”是否在userInput中。 例如:用户被输入“hello”,就会说它不是ab字。 例如:如果用户要键入“bag”,它会说这是一个ab字。 例如:如果用户键入“age”,它会说它不是ab字(因为缺少b)。你知道吗

我试过很多方法,包括使用计数器来计算字母表在字符串中的时间。 如果“a”和“b”在字符串内部,它将打印“inside”,否则如果其中一个不在内部或两者都不在内部,它将打印“notinside”

请帮帮我。我试过了,但效果不太好。你知道吗

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")

Tags: 字符串用户helloage键入returnifab
2条回答

检查你的情况

if (lastNum == "a" and "b"):

你的意思可能是

if (lastNum == "a" or lastNum == "b"):

但这也行不通。你可以用魔法数字。你知道吗

def tryword(x):        
    if x == '':
        return 0
    lastNum= x[-1]
    if (lastNum == "a"):
        return tryword(x[:-1]) | 1
    if (lastNum == "b"):
        return tryword(x[:-1]) | 2
    return tryword(x[:-1])

 assert tryword("qwer") == 0
 assert tryword("a") == 1
 assert tryword("b") == 2
 assert tryword("bb") == 2
 assert tryword("ab") == 3
 assert tryword("abababab") == 3

 def check_inside(s):
      if tryword(s) == 3:
           print "inside"
      else:
           print "not inside"

您需要添加两个累加器参数来跟踪是否找到每个字符。每个布尔值一个。你知道吗

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"

相关问题 更多 >