【Python CheckiO 题解】First Word (simplified)


CheckiO 是面向初学者和高级程序员的编码游戏,使用 Python 和 JavaScript 解决棘手的挑战和有趣的任务,从而提高你的编码技能,本博客主要记录自己用 Python 在闯关时的做题思路和实现代码,同时也学习学习其他大神写的代码。

CheckiO 官网:https://checkio.org/

我的 CheckiO 主页:https://py.checkio.org/user/TRHX/

CheckiO 题解系列专栏:https://itrhx.blog.csdn.net/category_9536424.html

CheckiO 所有题解源代码:https://github.com/TRHX/Python-CheckiO-Exercise


题目描述

【First Word (simplified)】:这个是 First Word 任务的简化版本,任务是找到一个字符串中的第一个单词(单词非字母),输入字符串仅包含英文字母和空格,字符串的开头和结尾没有空格。

【链接】https://py.checkio.org/mission/first-word-simplified/

【输入】:字符串

【输出】:字符串

【前提】:原字符串仅包含大小写字母和空格

【范例】

first_word("Hello world") == "Hello"

解题思路

以空格为分隔符,用 split() 方法将原字符串进行切片,返回第一个元素即可。

代码实现

def first_word(text: str) -> str:
    """
        returns the first word in a given text.
    """
    return text.split( )[0]


if __name__ == '__main__':
    print("Example:")
    print(first_word("Hello world"))
    
    # These "asserts" are used for self-checking and not for an auto-testing
    assert first_word("Hello world") == "Hello"
    assert first_word("a word") == "a"
    assert first_word("hi") == "hi"
    print("Coding complete? Click 'Check' to earn cool rewards!")

大神解答

大神解答 NO.1

def first_word(text: str) -> str:
    """
        returns the first word in a given text.
    """
    import re
    return(re.findall(r'^\w+',text)[0])

大神解答 NO.2

def first_word(text: str) -> str:
    """
        returns the first word in a given text.
    """
    try:
        text.find(' ')
        return text[0:int(text.index(' '))]
    except:
        return text

大神解答 NO.3

import re
def first_word(text: str) -> str:
    """
        returns the first word in a given text.
    """
    if " " not in text:
        return text
    else:
        ans = re.findall(r"\w+",text)
        ans = ans[0]
        return ans

大神解答 NO.4

def first_word(text):
    index = text.find(" ")
    return text[:index] if index != -1 else text


"""
It's worth to look at the performance of different methods under the same predefined conditions.
Let's check runtime of the 4 methods (10000 executions for each) defined below for the next 4 cases:
-a short str which contains space chars: "asdf we"*10;
-a short str which doesn't contain space chars: "asdfawe"*10;
-a long str which contains space chars: "asdf we"*100000;
-a long str which doesn't contain space chars: "asdf we"*100000.
############################################################################################################
from timeit import timeit as t


def first_word_1(text):
    return text.split(" ")[0]

print(t('first_word_1(x)', setup='x = "asdf we"*10', number=10000, globals=globals()))       #  ~11.7 ms
print(t('first_word_1(x)', setup='x = "asdfawe"*10', number=10000, globals=globals()))       #  ~6.1 ms
print(t('first_word_1(x)', setup='x = "asdf we"*100000', number=10000, globals=globals()))   #  ~90928.2 ms
print(t('first_word_1(x)', setup='x = "asdfawe"*100000', number=10000, globals=globals()))   #  ~5562.9 ms


def first_word_2(text):
    index = text.find(" ")
    return text[:index] if index != -1 else text
    
print(t('first_word_2(x)', setup='x = "asdf we"*10', number=10000, globals=globals()))       #  ~6.3 ms
print(t('first_word_2(x)', setup='x = "asdfawe"*10', number=10000, globals=globals()))       #  ~4.7 ms
print(t('first_word_2(x)', setup='x = "asdf we"*100000', number=10000, globals=globals()))   #  ~7.0 ms
print(t('first_word_2(x)', setup='x = "asdfawe"*100000', number=10000, globals=globals()))   #  ~2108.4 ms


def first_word_3(text):
    try:
        index = text.index(" ")
        return text[:index]
    except ValueError:
        return text

print(t('first_word_3(x)', setup='x = "asdf we"*10', number=10000, globals=globals()))       #  ~5.8 ms
print(t('first_word_3(x)', setup='x = "asdfawe"*10', number=10000, globals=globals()))       #  ~8.5 ms
print(t('first_word_3(x)', setup='x = "asdf we"*100000', number=10000, globals=globals()))   #  ~5.8 ms
print(t('first_word_3(x)', setup='x = "asdfawe"*100000', number=10000, globals=globals()))   #  ~2005.8 ms


def first_word_4(text):
    index = -1
    for pos, letter in enumerate(text):
        if letter == " ":
            index = pos
            break
    return text[:index] if index != -1 else text
    
print(t('first_word_4(x)', setup='x = "asdf we"*10', number=10000, globals=globals()))       #  ~13.1 ms
print(t('first_word_4(x)', setup='x = "asdfawe"*10', number=10000, globals=globals()))       #  ~71.1 ms
print(t('first_word_4(x)', setup='x = "asdf we"*100000', number=10000, globals=globals()))   #  ~13.1 ms
print(t('first_word_4(x)', setup='x = "asdfawe"*100000', number=10000, globals=globals()))   #  ~788793.7 ms
############################################################################################################
So what conclusions can be made from all of this?

1.Since every string is an instance of the string class, it's preferred to use its methods rather than implement
a new function which seems to be faster. It won't work faster in most of the cases. Compare first_word_2 and
first_word_4 for example.

2.Despite the fact first_word_1 (which uses .split() method) looks nice and concise it works worse with long strings
than first_word_2 and first_word_3 do(they use .find() and .index() methods respectively). Especially in case there are
lots of spaces in the text.

3.str.index() method works a bit faster than str.find() but only in case there is a space in the text. Otherwise it's
needed to handle an exception which takes some extra time. 

Thus, I'd use str.find() method in such kind of tasks.
"""
发布了135 篇原创文章 · 获赞 475 · 访问量 44万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 数字20 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览