python - 检查递归中的 2 个字符

标签 python recursion

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

相关文章:

python - 无法将输出转换为列表

python - 在Python中按顺序比较字符串中的字符

c - 具有随机输入的递归函数的时间复杂度

algorithm - 一个人在矩阵中移动 n 步的死亡概率

Javascript: 递归问题 --> 返回深度嵌套对象中最长的键值

python - 如何在 OSX High Sierra 中正确设置网状包的 Python 路径?

python - 如何使用libvlc向视频播放器添加其他音轨

python - iwlist 扫描输出格式

c++ - 如何删除此代码的重复排列?

sql - 查找行的财务模式 - 带递归的 sql