【问题标题】:Matching characters between 2 strings2个字符串之间的匹配字符
【发布时间】:2013-12-28 20:55:07
【问题描述】:

这段代码一直有问题。看来我对Python中while循环和缩进的理解还是不完整的。

在下面的代码中,我应该比较两个语句。如果第二个(搜索)语句中的字符在第一个(目标)语句中,则结果应为“True”。否则,打印“False”。

x = "I am a horse."
y = "a r"
  • targetn 引用目标字符串中的索引
  • searchn 指的是搜索字符串中的索引
  • letter 指目标字符串中的字符
  • word 指的是搜索字符串中的字符
def search_in_string(search, target):
    targetn = 0
    searchn = 0
    while (targetn + 1) != len(target):
        letter = target[targetn]
        word = search[searchn]
        if word == letter:
            targetn = targetn + 1
            searchn = searchn + 1
        if word != letter:        
            targetn = targetn + 1   
    if (searchn + 1) == len(searchn):
        return True
    else: 
        return False

print search_in_string(y, x)

在 Python 中运行代码时,由于searchn 超出范围,出现索引错误。我将不胜感激:

  1. 代码有什么问题和;
  2. 我对缩进和 while 循环的理解不完整。

【问题讨论】:

  • 能否请您澄清一下这个函数应该做什么?我认为您的问题在于逻辑,而不是缩进,但我不确定您要做什么。 (我最好的猜测是,当且仅当targetsearch 的子字符串时,它应该返回True。)
  • 对我来说,你的缩进看起来不错。我完全同意 Zack,你的逻辑似乎有点不对劲。但是我们不知道这个函数应该做什么。预期的输入和输出是多少?
  • 谢谢,我已经进行了编辑以澄清 - 是的,代码应该在最后返回 True 或 False。

标签: python string loops while-loop


【解决方案1】:

"1.代码有什么问题"

第 12 行的错字:应该是 len(search) 而不是 len(searchn)

Off-by-one 错误:如果 index==len(array) 那么它已经结束了。在所有索引测试中删除 + 1

第 4 行的剩余错误:在 while 条件下测试 targetnsearchn。根据字符串中的数据,任何一个都可以先结束。 (根据 luk32 的建议,将最终的 searchn 测试移动到循环内部,也可以修复此错误,但不适用于 search 为空或比目标更长的特殊情况。)

"2. 我对缩进和 while 循环的理解不完整。"

没有,但可能是列表和数组索引。

但更重要的是,函数和变量的命名不是很清楚,代码的风格看起来很像C。

命名

在当前代码中(带有错误修复)试试这个:

  • 将函数名search_in_string改为is_subsequence
  • 将变量名称search 更改为partial
  • 将变量名称target 更改为full
  • 同样将索引变量更改为ipartifull或类似
  • 完全删除变量letterword
  • 在测试中将 letter 替换为 full[ifull] 并将 word 替换为 partial[ipart]

现在不是更清楚了吗?

这里我还用明显的else 替换了补充的第二个if 测试:

def is_subsequence(partial, full):
    ifull = 0
    ipart = 0
    while ifull != len(full) and ipart != len(partial):
        if partial[ipart] == full[ifull]:
            ifull = ifull + 1
            ipart = ipart + 1
        else:
            ifull = ifull + 1
    if ipart == len(partial):
        return True
    else:
        return False

风格

程序风格看起来仍然像 C 语言,带有数组、显式循环和精细的索引操作。这是您了解一种称为“pythonic”的编码风格的机会。请参阅https://stackoverflow.com/questions/58968/what-defines-pythonian-or-pythonic 和那里的几个链接。

我会说 gnibbler 的答案是 Pythonic,但如果您不了解迭代器和列表理解,可能很难掌握。这是另一个有点pythonic的解决方案,我希望它更容易阅读。但是,您需要了解数组切片。

def is_subsequence(partial,full):
    for char in full:
        if partial.startswith(char):
            partial = partial[1:]
    return len(partial) == 0

【讨论】:

    【解决方案2】:

    我认为有一种更简单的方法来编写你的函数

    def search_in_string(search, target):
        iter_t = iter(target)
        return all(c in iter_t for c in search)
    

    例如:

    >>> search_in_string("a r", "I am a horse.")
    True
    >>> search_in_string("a re", "I am a horse.")
    True
    >>> search_in_string("a er", "I am a horse.")
    False
    

    【讨论】:

      【解决方案3】:

      没有进入代码的逻辑。

      编辑:好的,if 守卫的意图有误。 不过,长度为零的参数也是一个问题。

      x = "I am a horse."
      y = "a r"
      
      def search_in_string(search, target):
          targetn = 0
          searchn = 0
          while (targetn + 1) != len(target):
              letter = target[targetn]
              word = search[searchn]
              if word == letter:
                  targetn = targetn + 1
                  searchn = searchn + 1
              if word != letter:        
                  targetn = targetn + 1   
          #This will get executed AFTER the WHILE loop
          if (searchn + 1) == len(search):
              return True
          else: 
              return False
      
      print(search_in_string(x,y))
      

      工作代码:

      def search_in_string(search, target):
          targetn = 0
          searchn = 0
          while (targetn + 1) != len(target):
              letter = target[targetn]
              word = search[searchn]
              if word == letter:
                  targetn = targetn + 1
                  searchn = searchn + 1
              if word != letter:        
                  targetn = targetn + 1   
              #This will get executed WITHIN the WHILE loop
              if (searchn + 1) == len(search):
                  return True
              else: 
                  return False
      

      【讨论】:

        猜你喜欢
        • 2023-03-18
        • 1970-01-01
        • 2018-07-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-13
        • 1970-01-01
        相关资源
        最近更新 更多