美文网首页
[刷题]codewars - ReplaceWithAlphab

[刷题]codewars - ReplaceWithAlphab

作者: firewt | 来源:发表于2018-12-23 20:12 被阅读8次

原文链接:[刷题]codewars - ReplaceWithAlphabetPosition - 高歌的博客

直达链接:

Kata Stats: Replace With Alphabet Position | Codewars

题目描述:

Welcome.

In this kata you are required to, given a string, replace every letter with its position in the alphabet.

If anything in the text isn't a letter, ignore it and don't return it.

"a" = 1, "b" = 2, etc.

Example
alphabet_position("The sunset sets at twelve o' clock.")
Should return "20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11" (as a string)

思路

首先排除非英文,由于不区分大小写,所以,统一转为大写或小写,然后把在英文字母对应的ascii码范围内的字母找出,并减去ascii字母a对应的数字(91),加入列表中,最后列表排序。

代码:

def alphabet_position(text):
    target = []
    for i in text:
        n = ord(i.lower())
        if n in set(range(97,123)):
            target.append(str(n - 96))
    return ' '.join(target)

其它方法大同小异,下面是一个缩写成一句的方法:

def alphabet_position(text):
    return ' '.join(str(ord(c) - 96) for c in text.lower() if c.isalpha())

思考

最近接触到了一些团队项目,发现静态语言虽然繁琐,但是在团队协作时,统一规范中还是能带来很大好处的,而动态语言则没有这个优点,但是并不意味着动态语言就不适合团队项目,无论使用动态还是静态,开发前的团队规范都是必不可少的,例如:命名方法,事先约定,注释方式,文档要求……而且单元测试必不可少,正如erlang之父的一句话:动态语言绝对不是限制开发因素。那些嚷嚷着动态语言不如静态语言的人让他们用静态语言开发也一样糟糕。

相关文章

网友评论

      本文标题:[刷题]codewars - ReplaceWithAlphab

      本文链接:https://www.haomeiwen.com/subject/xqwxkqtx.html