首页 > 解决方案 > 列表中的 Python 算法

问题描述

在 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

标签: pythonpython-3.xalgorithm

解决方案


对您的代码的一些评论:

  • numpy如果只用于字符串比较,则无需使用
  • ii += 1当即将执行时未定义,因此不会运行。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)

推荐阅读