当前位置:首页 >> 编程语言 >> 【Python CheckiO 题解】First Word (simplified),360ak47

【Python CheckiO 题解】First Word (simplified),360ak47

0evadmin 编程语言 1
文件名:【Python CheckiO 题解】First Word (simplified),360ak47 【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 redef 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 msprint(t('first_word_1(x)', setup='x = "asdfawe"*10', number=10000, globals=globals())) # ~6.1 msprint(t('first_word_1(x)', setup='x = "asdf we"*100000', number=10000, globals=globals())) # ~90928.2 msprint(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 msprint(t('first_word_2(x)', setup='x = "asdfawe"*10', number=10000, globals=globals())) # ~4.7 msprint(t('first_word_2(x)', setup='x = "asdf we"*100000', number=10000, globals=globals())) # ~7.0 msprint(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 msprint(t('first_word_3(x)', setup='x = "asdfawe"*10', number=10000, globals=globals())) # ~8.5 msprint(t('first_word_3(x)', setup='x = "asdf we"*100000', number=10000, globals=globals())) # ~5.8 msprint(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 msprint(t('first_word_4(x)', setup='x = "asdfawe"*10', number=10000, globals=globals())) # ~71.1 msprint(t('first_word_4(x)', setup='x = "asdf we"*100000', number=10000, globals=globals())) # ~13.1 msprint(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 implementa new function which seems to be faster. It won't work faster in most of the cases. Compare first_word_2 andfirst_word_4 for example.2.Despite the fact first_word_1 (which uses .split() method) looks nice and concise it works worse with long stringsthan first_word_2 and first_word_3 do(they use .find() and .index() methods respectively). Especially in case there arelots 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'sneeded to handle an exception which takes some extra time. Thus, I'd use str.find() method in such kind of tasks."""
协助本站SEO优化一下,谢谢!
关键词不能为空
同类推荐
«    2025年12月    »
1234567
891011121314
15161718192021
22232425262728
293031
控制面板
您好,欢迎到访网站!
  查看权限
网站分类
搜索
最新留言
文章归档
网站收藏
友情链接