【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-testingassert 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 rereturn(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 textelse: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 tdef 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 msdef first_word_2(text):index = text.find(" ")return text[:index] if index != -1 else textprint(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 msdef first_word_3(text):try:index = text.index(" ")return text[:index]except ValueError:return textprint(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 msdef first_word_4(text):index = -1for pos, letter in enumerate(text):if letter == " ":index = posbreakreturn text[:index] if index != -1 else textprint(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. """總結
以上是生活随笔為你收集整理的【Python CheckiO 题解】First Word (simplified)的全部內容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: 感受下!最新财富自由标准公布:需要670
 - 下一篇: 4年前的OPPO Find X被罗永浩、