【每日一题0703】邓布利多教授的旅行

霍格沃茨学院新学期伊始,邓布利多教授打算拜访格兰芬多的新晋魔法师。他得到了每个魔法师的住 址,例如"432 Main Long Road St. Louisville OH 43071"作为一个名单。基本的邮政编码格式通常由两个大写字母、一个空格和五个数字组成。

要访问的客户列表是由所有地址组成的字符串,每个地址之间用逗号分隔,例如:

"123 Main Street St. Louisville OH 43071,432 Main Long Road St. Louisville OH 43071,786 High Street Pollocksville NY 56432"

任务

亲爱的魔法师让我们来编写一个函数,按邮政编码对列表进行分组吧,以便邓布利多教授的旅行。

函数 travel 将采用两个参数 r (表示所有客户端的地址列表作为字符串)和 zipcode(表示邮编),并返回以下格式的字符串:

zipcode:street and town,street and town,.../house number,house number,...

街道号码必须与它们所属的街道的顺序相同。如果给定的邮政编码不存在于客户端地址列表中,则返回“邮政编码:/”

示例

r = "123 Main Street St. Louisville OH 43071,432 Main Long Road St. Louisville OH 43071,786 High Street Pollocksville NY 56432"

travel(r, "OH 43071") 返回--> "OH 43071:Main Street St. Louisville,Main Long Road St. Louisville/123,432"
travel(r, "NY 56432") 返回--> "NY 56432:High Street Pollocksville/786"
travel(r, "NY 5643") 返回--> "NY 5643:/"

题目难度:简单
题目来源:codewars

def travel(address, zipcode):
    pass

ad = "123 Main Street St. Louisville OH 43071,432 Main Long Road St. Louisville OH 43071,786 High Street Pollocksville NY 56432"
assert travel(ad, "OH 43071") == "OH 43071:Main Street St. Louisville,Main Long Road St. Louisville/123,432"
assert travel(ad, "NY 56432") == "NY 56432:High Street Pollocksville/786"
assert travel(ad, "NY 5643") == "NY 5643:/"
def travel(r, s):
    tp = [" ".join(j.split(" ")[0:-2]) for j in r.split(',') if s == " ".join(j.split(" ")[-2:])]
    a = (",".join([f'{i[i.index(" ") + 1:]}' for i in tp]))
    b = (",".join([f'{i.split(" ")[0]}' for i in tp]))
    # print(f'{s}:{a}/{b}')
    return (f'{s}:{a}/{b}')

assert travel(r, "NY 56432") == "NY 56432:High Street Pollocksville/786"
assert travel(r, "OH 43071") == "OH 43071:Main Street St. Louisville,Main Long Road St. Louisville/123,432"
assert travel(r, "NY 5643") == "NY 5643:/"
def travel(r, zipcode):
    list1 = r.split(',')
    listkey = []
    nums = {}
    dic = {}
    for i in list1:
        list2 = i.split(' ')
        code = list2[-2]+" "+list2[-1]
        address = ' '.join(list2[1:-2])
        nums.setdefault(code,[]).append(list2[0])
        dic.setdefault(code,[]).append(address)
        if(code not in listkey):
            listkey.append(code)
    if(zipcode in listkey):
        val = ','.join(dic[zipcode]) + "/" + ','.join(nums[zipcode])
    else:
        val = "/"
    return zipcode + ":" + val
关闭