【每日一题0711】共同路径

给你一个完整文件名组成的列表,请编写一个函数,返回他们的共同目录路径。

题目难度:中等
题目来源:codewars

def get_common_path(path: list):
    pass
    
assert get_common_path(['/hogwarts/images/image1.png', '/hogwarts/images/image2.png']) == '/hogwarts/images/'
assert get_common_path(['/hogwarts/assets/style.css', '/hogwarts/scripts/app.js',  'home/setting.conf']) == ''
assert get_common_path(['/hogwarts/assets/style.css', '/.bin/mocha',  '/read.md']) == '/'

def get_common_path(path: list):
# 用’/‘分割取出所有path的子路径
li = [path[i].split(’/’) for i in range(len(path))]

# 取最浅路径
le = min([len(i) for i in li])

# 比较所有的路径,存在相同的路径添加到com列表中
com = []
for i in range(le):
    for j in range(len(li)-1):
        flag = 0
        if li[j][i] != li[j+1][i]:
            flag = 1
            break
    if flag == 0:
        com.append(li[j][i])

# 没有共同路径
if len(com) == 0:
    return ''
# 仅有共同根路径
if len(com) == 1:
    return '/'
return '/'.join(com) + '/'
def get_common_path(path: list=None):
    """
    解题思路:对每个子路径,从0位开始比较的字符是否相同,相同则往后推,遇到不相同的字符则退出,
    需要注意的是,比较的同时要记录"/"的位置slash_index,最后返回结果则是从0到slash_index位置的字符串
    """
    index = 0
    slash_index = 0
    while True:
        try:
            item = [sub[index] for sub in path]
            if len(set(item)) == 1:
                index += 1
                if list(set(item)) == ['/']:
                    slash_index = index
            else:
                break
        except:
            break
    return path[0][:slash_index]
def get_common_path(path: list):
    data = list(zip(*path))
    
    cursor = 0
    for i in range(len(data)):
        if len(set(data[i])) != 1:
            cursor = i
            break

    return path[0][:path[0][:cursor].rfind('/')+1]
    
assert get_common_path(['/hogwarts/images/image1.png', '/hogwarts/images/image2.png']) == '/hogwarts/images/'
assert get_common_path(['/hogwarts/assets/style.css', '/hogwarts/scripts/app.js',  'home/setting.conf']) == ''
assert get_common_path(['/hogwarts/assets/style.css', '/.bin/mocha',  '/read.md']) == '/'

:partying_face: :partying_face: :partying_face: :partying_face: :partying_face: :partying_face:

关闭