【问题标题】:comparing two strings and their index seeing if all of string 2 is in string 1 with same order but different letter in between比较两个字符串及其索引,看看是否所有字符串 2 都在字符串 1 中,顺序相同但字母不同
【发布时间】:2020-02-14 21:00:56
【问题描述】:

假设给定单词中的所有字母都是小写的。 如果有用的话,你可以使用字符串方法。

>>> occurs_within('aaacaabxyt', 'cat')
True

>>> occurs_within('tac', 'cat')
False

>>> occurs_within('oboe', 'bob')
False

>>> occurs_within('ecxbtalt', 'exalt')
True

>>> occurs_within('ecxbtal', 'exalt')
False

if len(word1) > len(word2):
    for i in range(0,len(word1)):
        if word2[i] < word2[i+1]:
            return True
        else:
            return False
else:
    return False

我尝试在 if 函数中使用嵌套 for 循环比较两个字符串并循环查找字符串 1 中的字符串 2 的下一个索引是否大于前一个索引的索引,但结果是我的结果不知何故都是真实的,我无法弄清楚似乎是什么问题。

【问题讨论】:

标签: python for-loop


【解决方案1】:

海象练习:-)

def occurs_within(s, t):
    i = 0
    return all((i := s.find(c, i) + 1) for c in t)

【讨论】:

  • 不是总是返回True吗?我的意思是,str.find 在失败时返回 -1……
  • @Błotosmętek 不,它返回False,例如occurs_within('ab', 'ba')。不知道你(和反对者?)是如何误解代码的。
  • @HeapOverflow 不知道为什么这被否决了。但是这个问题可以在O(n)时间解决。
  • @Ch3steR 不知道你为什么这么说。我的解决方案是 O(n)。并且可能相当快,因为​​它允许字符串搜索本身(即快速 C 代码)。
  • @HeapOverflow 好的,我明白了 - -1 + 1False :-) 我想我对海象还不够熟悉。
【解决方案2】:

要查找单词 word 是否 - 由于缺少更好的单词 - “嵌入”在字符串 s 中,您需要找到单词第一个字母在字符串中的位置,然后是第二个字母在字符串的其余部分(即超过第一个字母的位置)等。如果在任何阶段您未能找到下一个字母,则返回False。这段代码做到了:

def occurs_within(s, word):
    pos = 0
    for letter in word:
        i = s.find(letter, pos)
        if i == -1:
            return False
        pos = i+1
    return True

【讨论】:

    【解决方案3】:

    让我们“橡皮鸭”:

    # if word 1 is longer than word two
    if len(word1) > len(word2):
       # lets `enumerate()` or look at each index of word 1 , 
       # and see if it is in word 2
        for i in range(0,len(word1)):
            # if the letter of word2 at index "i" is less than
            # the letter of word2 at "i + 1" then return true
            #############
            # notice you're trying to compare using a relational operator "<"
            # which would be 
            # "a" < "a" == False 
            # "b" < "a" == False
            # "a" < "b" == True
            # for example:
            #     'oboe', 'bob'
            #     (w1 letter, index, w2 letter)
            #     o, 0, b < o == True
            #     b, 1, o < b == False
            #     o, 2, b < None
            #     e, 3, None < None
            # this doesn't work because word2 isn't alphabetical.
            # and the len() of word2 in these examples are not longer than     
            # word1. For example ["t", "a", "c"][2] and ["c", "a", "t"][2+1] 
            if word2[i] < word2[i+1]:
                # end the function by returning true
                # the loop will not continue to check the rest of the word
                return True
            else:
                return False
    # word 1 is not longer than word 2
    else:
        return False
    

    见:

    【讨论】:

    • 当实际代码只比较 w2 和不同索引处的字母时,为什么您的 cmets 比较来自 w1 和 w2 的相同索引处的字母?既然第一个比较之后已经有return,为什么还要讨论多个比较?
    • @HeapOverflow 感谢更新。请参阅:for i in range(0,len(word1)): w1 索引正在用于索引 w2。
    • 啊,我看错了。现在看到Nones。你所说的“w2 字母”并不是真正的 w2 字母,而是一种比较,在我看来,它就像是 word2[i]word1[i] 的比较。选择的示例确实使它看起来像前两次迭代一样无济于事:-)
    【解决方案4】:

    您可以为此使用正则表达式匹配。

    import re
    
    def occurs_within(word1, word2):
        #build regex, basically inserting '.*' around any character in word2. In a regex, '.*' means any character any amount of time (even 0)
        regex = '.*{}.*'.format('.*'.join(list(word2)))
    
        #matching
        return bool(re.match(regex, word1))
    

    【讨论】:

      【解决方案5】:

      如果您发现当前字母是您的第二个字符串中的那个,您可以逐个字母地迭代第一个单词。

      def occurs_within(str1, str2):
          index = 0
          if len(str2) > len(str1):
              return False
          if str1 == str2:
              return True
          else:
              word = []
              index = 0
              for letter in str1:
                  if index == len(str2):
                      break
                  if letter == str2[index]:
                      index += 1
                      word.append(letter)
              print(word)
              return ''.join(word) == str2
      

      【讨论】:

        【解决方案6】:

        你可以试试这个。花点时间O(n)

        def func(a,b):
             a1=len(a)
             b1=len(b)
             i,j=0,0
             while(i<a1 and j<b1):
                 if a[i]==b[j]:
                     j=j+1
                 i=i+1
             return j==b1
        

        >>> func('aaacaabxyt', 'cat')
        True
        >>> func('tac', 'cat')
        False
        >>> func('oboe', 'bob')
        False
        >>> func('ecxbtalt', 'exalt')
        True
        >>> func('ecxbtal', 'exalt')
        False
        

        【讨论】:

          【解决方案7】:

          我已经用大量的单词和子词示例对其进行了测试,这对它们中的每一个都有效。

          def occurs_within(word, sub_word):
              letter_at = -1
              for letter in sub_word:
                  temp = letter_at
                  letter_at = word.find(letter, temp + 1)
                  if 0 < letter_at <= temp or letter_at == -1:
                      return False
              return True
          

          基本上背后的逻辑是,为了让函数返回True,你需要循环sub_word并测试每个字母,如果该字母存在于word中,以及该字母的索引在该字符串中 (word) 必须大于测试的sub_word 的最后一个字母。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2014-05-15
            • 2022-11-07
            • 1970-01-01
            • 2011-12-23
            • 1970-01-01
            • 2022-01-02
            • 2014-02-23
            相关资源
            最近更新 更多