CCF-201803-3-URL映射

题意:
给出几条规则和url,判断每条url是否有匹配规则,有就输出规则名字和匹配参数。

这题题目说的不够细,url后面有‘/’的只能和后面也有‘/’的规则匹配。例如url:/abc/def/ 和 规则:/abc/def 是不能匹配的。然后后面没有‘/’的url只能和后面没有‘/’的规则匹配(path与有结束的url匹配)。以前不懂,现在才想到这个地方,修改下代码就终于100了。

python代码:

# 匹配url和规则
def match(url, rule, args):
    while url and rule:
        u, r = url.pop(0), rule.pop(0)
        if r == '<int>' and u.isdigit():
            args.append(u)
        elif r == '<str>' and not u.isdigit() and u:  # 如果该规则项是str,且该url项非空非数字
            args.append(u)
        elif r == '<path>' and url[-1]:
            path = [u]
            while url:
                path.append(url.pop(0))
            args.append('/'.join(path))
        elif u == r:
            continue
        else:
            return False
    return False if url or rule else True


n, m = map(int, input().split())
rules = []
for i in range(n):
    rules.append(input().split())

for i in range(m):
    url = input().split('/')[1:]  # 处理url,如果结尾有‘/’,列表最后一项是空字符串。
    for rule, name in rules:
        rule = rule.split('/')[1:]  # 处理规则,同上理
        args = []  # 匹配参数
        # 判断是否匹配这条规则,匹配就打印
        if match(url[:], rule[:], args):
            print(name, end=' ')
            [print(int(e) if e.isdigit() else e, end=' ') for e in args]
            print()
            break
    # 所有规则都不匹配就404
    else:
        print('404')

# 5 4
# /articles/2003/ special_case_2003
# /articles/<int>/ year_archive
# /articles/<int>/<int>/ month_archive
# /articles/<int>/<int>/<str>/ article_detail
# /static/<path> static_serve
# /articles/2004/
# /articles/1985/09/aloha/
# /articles/hello/
# /static/js/jquery.js
#

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值