Python-7:巧妙算法匹配标题创意,激发无限创意灵感

问题描述

在广告平台中,为了给广告主一定的自由性和效率,允许广告主在创造标题的时候以通配符的方式进行创意提交。线上服务的时候,会根据用户的搜索词触发的 bidword 对创意中的通配符(通配符是用成对 {} 括起来的字符串,可以包含 0 个或者多个字符)进行替换,用来提升广告投放体验。例如:“{末日血战} 上线送 SSR 英雄,三天集齐无敌阵容!”,会被替换成“帝国时代游戏下载上线送 SSR 英雄,三天集齐无敌阵容!”。给定一个含有通配符的创意和n个标题,判断这句标题是否从该创意替换生成的。

代码

import re

def solution(n, template_, titles):

    # Please write your code here

    assert n == len(titles)

    if "{" not in template_:

        return [template_ == s for s in titles]

    p, q = template_.find('{'), template_.rfind('}')

    st, ed = template_[:p], template_[q + 1:]

    template_ = template_[p:q + 1]

    subs = re.findall(r'[^{}]+(?=\{)|(?<=\})[^{}]+|^[^{]+|[^}]+$', template_)

    def ok(subs, s: str):

        if not (len(s) >= len(st) + len(ed) and s.startswith(st) and s.endswith(ed)):

            return False

        p = 0

        for t in subs:

            q = s.find(t, p)

            if q == -1:

                return False

            p = q + len(t)

        return True

    return ','.join(map(str, [ok(subs, s) for s in titles]))

if __name__ == "__main__":

    #  You can add more test cases here

    testTitles1 = ["adcdcefdfeffe", "adcdcefdfeff", "dcdcefdfeffe", "adcdcfe"]

    testTitles2 = ["CLSomGhcQNvFuzENTAMLCqxBdj", "CLSomNvFuXTASzENTAMLCqxBdj", "CLSomFuXTASzExBdj", "CLSoQNvFuMLCqxBdj", "SovFuXTASzENTAMLCq", "mGhcQNvFuXTASzENTAMLCqx"]

    testTitles3 = ["abcdefg", "abefg", "efg"]

    print(solution(4, "ad{xyz}cdc{y}f{x}e", testTitles1) == "True,False,False,True" )

    print(solution(6, "{xxx}h{cQ}N{vF}u{XTA}S{NTA}MLCq{yyy}", testTitles2) == "False,False,False,False,False,True" )

    print(solution(3, "a{bdc}efg", testTitles3) == "True,True,False" )

作者:完成大叔

物联沃分享整理
物联沃-IOTWORD物联网 » Python-7:巧妙算法匹配标题创意,激发无限创意灵感

发表回复