【问题标题】:Python algorithm in list列表中的 Python 算法
【发布时间】:2021-02-21 08:23:58
【问题描述】:

在 N 个字符串的列表中,实现一个算法,如果整个字符串与前面的 n 个字符串相同,则输出最大的 n。 (即,打印出所有给定字符串前面有多少个字符匹配)。

我的代码:

def solution(a):
    import numpy as np
    for index in range(0,a):
        if np.equal(a[index], a[index-1]) == True:
            i += 1
            return solution
        else:
            break

    return 0
 
# Test code
print(solution(['abcd', 'abce', 'abchg', 'abcfwqw', 'abcdfg'])) # 3
print(solution(['abcd', 'gbce', 'abchg', 'abcfwqw', 'abcdfg'])) # 0

【问题讨论】:

  • 请正确解释您的问题。有一个样本所需的输入和输出。另外,在这里使用numpy 可能有点过头了。
  • 为什么要增加 i ?而且你也没有使用它。

标签: python python-3.x algorithm


【解决方案1】:

您的代码中的一些 cmets:

  • numpy如果只用于字符串比较就不用了
  • i += 1 即将执行时,i 未定义,因此不会运行。您的代码中没有实际使用i
  • index-1 是循环第一次迭代中列表索引的无效值
  • solution 是你的函数,所以 return solution 将返回一个函数对象。您需要返回一个数字。
  • if 条件仅比较完整的单词,因此不会尝试仅比较前缀。

一种可能的方法是保持乐观并假设第一个单词是所有其他单词的前缀。然后,当您检测到不是这种情况的单词时,减小前缀的大小,直到它再次成为该单词的有效前缀。像这样继续,直到所有单词都被处理完。如果在任何时候你发现前缀被缩减为一个空字符串,你实际上可以退出并返回 0,因为它不能小于这个值。

你可以这样编码:

def solution(words):
    prefix = words[0]  # if there was only one word, this would be the prefix
    for word in words:
        while not word.startswith(prefix):
            prefix = prefix[:-1]  # reduce the size of the prefix
            if not prefix:  # is there any sense in continuing?
                return 0  # ...: no.
    return len(prefix)

【讨论】:

    【解决方案2】:

    描述有些复杂,但您似乎正在寻找最长公共前缀的长度。

    您可以使用 next() 函数获取两个字符串之间公共前缀的长度。它可以找到字符不同的第一个索引,这将对应于公共前缀的长度:

    def maxCommon(S):
        cp = S[0] if S else "" # first string is common prefix (cp)
        for s in S[1:]:        # go through other strings (s)
            cs = next((i for i,(a,b) in enumerate(zip(s,cp)) if a!=b),len(cp))
            cp = cp[:cs]       # truncate to new common size (cs)
        return len(cp)         # return length of common prefix
    

    输出:

    print(maxCommon(['abcd', 'abce', 'abchg', 'abcfwqw', 'abcdfg'])) # 3
    print(maxCommon(['abcd', 'gbce', 'abchg', 'abcfwqw', 'abcdfg'])) # 0
    

    【讨论】:

      猜你喜欢
      • 2020-11-02
      • 2011-03-26
      • 2016-06-13
      • 1970-01-01
      • 2020-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多