为什么不遵守我的返回命令?

安德鲁·里维拉(Andrew Rivera)

我正在尝试编写一个函数来从一系列字符串中返回最长的公共前缀。使用调试器,我的函数正确地到达了最长的公共前缀,但是当它到达要返回的语句时,它开始恢复到算法的早期阶段。

对于测试用例 strs = ["flower","flow","flight"]

输出变量具有以下值:

f > fl > f

而不是返回fl

任何帮助将不胜感激,因为我真的不知道该如何使用Google。谢谢。

class Solution(object):
def longestCommonPrefix(self, strs, output = ''):
    #return true if all chars in string are the same
    def same(s):
        return s == len(s) * s[0]
    
    #return new list of strings with first char removed from each string
    def slicer(list_, list_2 = []):
        for string in list_:
            string1 = string[1:]
            list_2.append(string1)
        return list_2
    
    #return string containing first char from each string
    def puller(list_):
        s = ''
        for string in list_:
            s += string[0]
        return s
    
    #pull first character from each string
    s = puller(strs)
    
    #if they are the same
    #add one char to output
    #run again on sliced list
    if same(s):
        output += s[0]
        self.longestCommonPrefix(slicer(strs), output)            
    
    return output
马修·德维尔纳

可以使用来处理os.path.commonprefix

>>> import os
>>> strs = ["flower","flow","flight"]
>>> os.path.commonprefix(strs)
'fl'

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章