繁体   English   中英

列表中的 Python 算法

[英]Python algorithm in list

在 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 += 1即将执行时, i未定义,因此不会运行。 i在您的代码中没有实际使用。
  • index-1是循环第一次迭代中列表索引的无效值
  • solution是您的 function,因此return solution将返回 function object。 您需要返回一个数字。
  • 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)

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

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

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

output:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM