问题描述:

As breadcrumb menùs are quite popular today, I won't digress much on explaining them, leaving the wiki link to do all the dirty work in my place.

What might not be so trivial is instead to get a decent breadcrumb from your current url. For this kata, your purpose is to create a function that takes a url, strips the first part (labelling it always HOME) and then builds it making each element but the last a <a> element linking to the relevant path; last has to be a <span> element getting the active class.

All elements need to be turned to uppercase and separated by a separator, given as the second parameter of the function; the last element can terminate in some common extension like .html.htm.php or .asp; if the name of the last element is index.something, you treat it as if it wasn't there, sending users automatically to the upper level folder.

A few examples can be more helpful than thousands of words of explanation, so here you have them:

generate_bc("mysite.com/pictures/holidays.html", " : ") == '<a href="/">HOME</a> : <a href="/pictures/">PICTURES</a> : <span class="active">HOLIDAYS</span>'
generate_bc("www.codewars.com/users/GiacomoSorbi", " / ") == '<a href="/">HOME</a> / <a href="/users/">USERS</a> / <span class="active">GIACOMOSORBI</span>'
generate_bc("www.microsoft.com/docs/index.htm", " * ") == '<a href="/">HOME</a> * <span class="active">DOCS</span>'

Seems easy enough?

Well, probably not so much, but we have one last extra rule: if one element (other than the root/home) is longer than 30 characters, you have to shorten it, acronymizing it (i.e.: taking just the initials of every word); url will be always given in the format this-is-an-element-of-the-url and you should ignore words in this array while acronymizing: ["the","of","in","from","by","with","and", "or", "for", "to", "at", "a"]; a url composed of more words separated by - and equal or less than 30 characters long needs to be just uppercased with hyphens replaced by spaces.

Ignore anchors (www.url.com#lameAnchorExample) and parameters (www.url.com?codewars=rocks&pippi=rocksToo) when present.

Examples:

generate_bc("mysite.com/very-long-url-to-make-a-silly-yet-meaningful-example/example.htm", " > ") == '<a href="/">HOME</a> > <a href="/very-long-url-to-make-a-silly-yet-meaningful-example/">VLUMSYME</a> > <span class="active">EXAMPLE</span>'
generate_bc("www.very-long-site_name-to-make-a-silly-yet-meaningful-example.com/users/giacomo-sorbi", " + ") == '<a href="/">HOME</a> + <a href="/users/">USERS</a> + <span class="active">GIACOMO SORBI</span>'

You will always be provided valid url to webpages in common formats, so you probably shouldn't bother validating them.

If you like to test yourself with actual work/interview related kata, please also consider this one about building a string filter for Angular.js.

Special thanks to the colleague that, seeing my code and commenting that I worked on that as if it was I was on CodeWars, made me realize that it could be indeed a good idea for a kata :)

代码实现:

#codewars第二十一题(繁琐)
def generate_bc(url, separator):if '//' in url:url = url[url.index('//') + 2:]url = url.rstrip('/')try:for i, c in enumerate(url):if c in ['?', '#']:url = url[0:i]breakmenus = url.split('/')[1:]if menus and 'index.' == menus[-1][0:6]:menus = menus[:-1]if not menus:return '<span class="active">HOME</span>'breadcrumb = '<a href="/">HOME</a>'for i, e in enumerate(menus[:-1]):breadcrumb += separator + '<a href="/{}/">{}</a>'.format('/'.join(menus[:i + 1]), get_element_name(e))breadcrumb += separator + '<span class="active">{}</span>'.format(get_element_name(menus[-1]))return breadcrumbexcept:return urlignore_words = ["the", "of", "in", "from", "by", "with", "and", "or", "for", "to", "at", "a"]def get_element_name(element):acronyms = element.split('-')for i, c in enumerate(acronyms[-1]):if c == '.':acronyms[-1] = acronyms[-1][:i]breakif len(element) > 30:for i, c in reversed(list(enumerate(acronyms))):if c in ignore_words:acronyms.pop(i)return ''.join([s[0].upper() for s in acronyms])return ' '.join([s.upper() for s in acronyms])#另解
from re import subignoreList = ["THE", "OF", "IN", "FROM", "BY", "WITH", "AND",  "OR",  "FOR",  "TO",  "AT",  "A"]def generate_bc(url, separator):# remove leading http(s):// and trailing /url = sub("https?://", "", url.strip("/"))# skip index filesurl = sub("/index\..+$", "", url)# split url for processingurl = url.split("/")# remove file extensions, anchors and parametersurl[-1] = sub("[\.#\?].*", "", url[-1])# first element is always "home"menu = ["HOME"]# generate breadcrumb itemsfor item in url[1:]:# replace dashes and set to uppercaseitem = sub("-", " ", item.upper())# create acronym if too longif len(item) > 30:item = "".join([w[0] for w in item.split() if w not in ignoreList])menu.append(item)# generate pathspath = ["/"]for i in range(len(url) - 1):path.append(path[i] + url[i+1] + "/")# generate html codehtml = []for i in range(len(url) - 1):html.append("<a href=\"" + path[i] + "\">" + menu[i] +"</a>")html.append("<span class=\"active\">" + menu[-1] +"</span>")return separator.join(html)

【Codewars python 4kyu】: Breadcrumb Generator相关推荐

  1. 2021年【大学生Python学习】社区小博主【孤寒者】的年度总结

    文章目录: 第一部分-2021年[大学生]社区年度总结: 一.2021年社区回顾 二.2021年年度总结--优秀社区成员表彰 前六名: 七到十名: 三.社区简介: (社区)2021年圆满落幕,展望20 ...

  2. 【数据结构Python描述】优先级队列描述“银行VIP客户插队办理业务”及“被插队客户愤而离去”的模型实现

    文章目录 一.支持插队模型的优先级队列 队列ADT扩充 队列记录描述 方法理论步骤 `update(item, key, value)` `remove(item)` 二.支持插队模型的优先级队列实现 ...

  3. 【数据结构Python描述】树的简介、基本概念和手动实现一个二叉树

    文章目录 一.树的简介 1. 树的定义 2. 相关概念 二.树的ADT 三.树的实现准备 1. 树的基本分类 2. 树的抽象基类 四.树的概念拾遗 1. 深度 2. 高度 五.二叉树的简介 1. 定义 ...

  4. 【初识python 1】Python PPT PDF 转成图片

    序言   由于业务需求需要实现文档转成图片输出,PHP实现效率不是很高(libreoffice,ImageMagick,unoconv,wkhtmltopdf等),尝试用python做个小尝试,目前只 ...

  5. 【初识python 3】PPT PDF 转图片优化告一段落

    序言 不想起标题,将就看吧 ^ _ ^ 看此片文章之前请先阅读 [初识python 1]Python PPT PDF 转成图片 [初识python 2]对服务端发送PDF EXCEL文件URL转成图片 ...

  6. pb 如何导出csv_backtrader如何加载股票因子数据?以换手率、市盈率为例进行回测【附Python代码】

    1引言 关于backtrader,公众号已连续发布了三篇推文:<[手把手教你]入门量化回测最强神器backtrader(一)>.<[手把手教你]入门量化回测最强神器backtrade ...

  7. 【数据结构Python描述】手动实现一个list列表类并分析常用操作时间复杂度

    文章目录 一.使用动态数组实现列表 1. 动态数组概念引入 2. 验证列表实现策略 3. 动态数组算法实现 二.摊销法分析时间复杂度 1. 摊销法使用示例 2. 数组容量指数增长 3. 数组容量等差增 ...

  8. 【ASE+python学习】-批量识别石墨烯团簇结构中的吡啶氮,并删除与其相连的氢

    批量识别石墨烯团簇结构中的吡啶氮,并删除与其相连的氢 文章背景 任务内容 程序实现思路 实现代码 建立标准结构中边缘碳与氢的位置差值标准数据集 读入待修改结构,识别氮与氢位置差值是否存在标准数据集 代 ...

  9. 【天池-Python训练营】Task3学习笔记

    文章目录 0.前言 1.函数 1.1 函数的定义 1.2 函数的调用 1.3 函数文档 1.4 函数参数 1.5 函数的返回值 1.6 变量作用域 2.Lambda 表达式 2.1 匿名函数的定义 2 ...

最新文章

  1. c语言怎么创建一个h文件,求助C语言大佬 , 只会写到一个.c文件里 ,不会用.h头文件...
  2. [Android Pro] 利用tcpdump和wireshark对android网络请求进行分析
  3. codis 部署和测试
  4. servlet实现文件上传,预览,下载和删除
  5. formula 返回list_python正则实现计算器功能
  6. ROS----龟界三角恋
  7. C++之文件操作探究(三):写文件——二进制文件
  8. Chrome浏览器截取全屏(无需安装任何插件)
  9. 注册电气工程师有多难考呢?注册电气工程师通过率是多少
  10. 基于ThinkPHP6+Layui的后台管理框架
  11. java 数据可视化_8个可靠的开源数据可视化工具
  12. 数据增强:模拟雨天算法Python
  13. 基于FL2440 的V4L2采集 + H264编码 + LIVE555发布的实时视频监控系统
  14. 【Paper】Neural Machine Translation by Jointly Learning to Align and Translate
  15. 传播正能量——做一个快乐的程序员
  16. (十二)苏世民:我的经验和教训:苏世民带领黑石走向巅峰的十大管理原则
  17. 使用新浪微博登录组件
  18. 【Maven】---Linux搭建Nexus3.X私服
  19. sap 用户权限表_sap权限相关后台表
  20. VMware虚拟机软件安装国产操作系统 统信 UOS V20 1050e 手把手保姆教程

热门文章

  1. 【史上最骚爬虫|疯狂爬取中国大学mooc】太燃了,爬虫vs慕课反爬世纪大战|No.1
  2. 企业级360°全方位用户画像:标签系统[四]
  3. 【MOOC】数学实验 - 电子科技大学-第1讲
  4. 江苏财经职业技术学校计算机专业怎么样,江苏财会职业学院好不好?排名怎么样评价如何...
  5. OJB Connection
  6. 【转】整整30天终于走完,分享下我的昆山人才引进落户经历
  7. ajax获取涨停股票接口,80后股神研究的两个涨停买入法!(图解)
  8. CheckBox复选框
  9. 车载微信助手服务器异常,同步助手/微信备份助手遇到服务器访问异常怎么办?...
  10. 【数学】焦点弦定理(?)