【每日一题0615】 获取 list 最长公共前缀

获取 list 最长公共前缀

例:
[“flower”,“flow”,“flight”] 输出"fl"
[‘cat’,‘hello’] 输出为空字符串

def getComonPre(l:list):
    """ 获取 最大的共同长度 """
    # l = ['flower','22','flight']
    com_pre=''
    if len(l) == 0:
        return ''
    shortest = min(l, key=len) #获取list中最短的一个
    for i in range(len(shortest)):
        # print(f'前{i}个是:{shortest[:i]}')
        flag = False   # 判断shortest退出循环
        for item in l:
            if shortest[i] != item[i]:
                com_pre = shortest[:i]
                flag = True
                break
        if flag:
            break
    return com_pre
def findLongestPrefix(strs) :
    if strs==[]:
        return ''
    else:
        a = strs[0]
    for i in strs:
        while (i.startswith(a) == False):
            a=a[:len(a)-1]
    return a
def func0615(sss):
    for k in range(len(sss[0])):
        for m in range(1,len(sss)):
            if sss[0][k] != sss[m][k]:
                return  sss[0][0:k]
print(func0615(['flower', 'flow', 'flight']))
"""
例:
[“flower”,“flow”,“flight”] 输出"fl"
[‘cat’,‘hello’] 输出为空字符串
"""


def test(str_list: list):
    n = 0
    max_num = min([len(i) for i in str_list])
    flag = True
    while n < max_num and flag:
        for i in range(1, len(str_list)):
            if str_list[i][n] != str_list[i - 1][n]:
                flag = False
                break
        else:
            n += 1

    return str_list[0][0:n]


assert test(["flower", "flow", "flight"]) == "fl"
assert test(["cat", "hello"]) == ""
# 数组越界
assert test(["ces1", "ce", "cessss"]) == "ce"

题解思路:
第一步:先把所有单词按字母位置进行归集
第二步:从前往后依次过滤出元素全部相同的子元组,此题目适合短路操作,遇到非则停
第三步:提取出所有相同的前缀字母

import itertools

def longest_prefix(li:list):
    
    flat_data = list(itertools.zip_longest(*tuple(li)))
    same_list = list(itertools.takewhile(lambda x:len(set(x))==1, flat_data))
    return ''.join([item[0] for item in same_list])

assert longest_prefix(["flower","flow","flight"]) == 'fl'
assert longest_prefix(["cat","hello"]) == ''

哈哈哈,周末终于有空了,赶紧把之前漏的题都做起来~~~
:partying_face: :partying_face: :partying_face: :partying_face: :partying_face: :partying_face:

def solution(strs) -> str:
    if not strs:
        return ''
    result = '''
    for s in zip(*strs):
        set_s = set(s)
        if len(set_s) == 1:
            result += s[0]
        else:
            break
    return result

参考大神的自己写了写,感觉自己写的好low

def get_prefix(li:list):
    li2=tuple(li) #转化为元组
    data=list(itertools.zip_longest(*li2))
    # print(list(data))
    same_data=list(itertools.takewhile(lambda x:len(set(x))==1,data))
    # print(same_data)
    res=''
    for items in list(same_data):
        res=res+items[0]
    return res
关闭