python - 列表中的 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
解决方案
对您的代码的一些评论:
numpy
如果只用于字符串比较,则无需使用i
i += 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)
推荐阅读
- ios - 登录视图控制器不想在登录后关闭
- python - 有没有办法使用 webbrowser.open 打开新浏览器而不是新标签
- javascript - 未捕获的类型错误:在 JS 中 this.changeRoundScore 不是 HTMLButtonElement.roll (app.js:35) 的函数
- c# - C#从串口读取四个字节的无符号二进制数的问题
- java - 当 textarea 与其他组件一起使用时,为什么 Java pack 无法正确调整框架大小?
- node.js - Nodejs Express https到http重定向不起作用
- android - 安卓工作室中的亚行
- nginx - 基于 http_cookie 偏好的国家代码重写到 Nginx 上的相应站点
- python - 默认情况下,如何查看 Series 和/或 DataFrame 中的所有行?
- python - 如何使用元组列表对压缩字典进行排序?