当前位置:首页 >> 编程语言 >> 【Python CheckiO 题解】Second Index,暴风影音事件

【Python CheckiO 题解】Second Index,暴风影音事件

0evadmin 编程语言 1
文件名:【Python CheckiO 题解】Second Index,暴风影音事件 【Python CheckiO 题解】Second Index

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


题目描述

【Second Index】:给定两个字符串,要查找第二个字符在第一个字符串中第二次出现的位置

【链接】:https://py.checkio.org/mission/second-index/

【输入】:两个字符串

【输出】:位置(int)或者 None

【范例】:

second_index("sims", "s") == 3second_index("find the river", "e") == 12second_index("hi", " ") is None 解题思路

首先循环访问第一个字符串(text)中的所有字符,当字符与给定的第二个字符(symbol)相同时,记录此时字符的位置,将每个位置添加到一个新列表中,最后判断,如果列表长度大于等于 2,则表示该字符(symbol)在原字符串(text)中出现次数大于等于 2,最后返回第二次出现的位置即可(um_list[1])。

代码实现 def second_index(text: str, symbol: str) -> [int, None]:"""returns the second index of a symbol in a given text"""num_list = []for i in range(len(text)):if symbol == text[i]:num_list.append(i)if len(num_list) >= 2:return num_list[1]if __name__ == '__main__':print('Example:')print(second_index("sims", "s"))# These "asserts" are used for self-checking and not for an auto-testingassert second_index("sims", "s") == 3, "First"assert second_index("find the river", "e") == 12, "Second"assert second_index("hi", " ") is None, "Third"assert second_index("hi mayor", " ") is None, "Fourth"assert second_index("hi mr Mayor", " ") == 5, "Fifth"print('You are awesome! All tests are done! Go Check it!') 大神解答 大神解答 NO.1 def second_index(text: str, symbol: str) -> [int, None]:try:return text.replace(symbol, '', 1).index(symbol) + 1except:return None 大神解答 NO.2 def second_index(text: str, symbol: str) -> [int, None]:return text.index( symbol, text.index( symbol ) + 1 ) if text.count( symbol ) > 1 else None 大神解答 NO.3 def second_index(text: str, symbol: str) -> [int, None]:if text[text.find(symbol)+1:].find(symbol) == -1:return Noneelse:return text.find(symbol, text.find(symbol)+1)
协助本站SEO优化一下,谢谢!
关键词不能为空
同类推荐
«    2025年12月    »
1234567
891011121314
15161718192021
22232425262728
293031
控制面板
您好,欢迎到访网站!
  查看权限
网站分类
搜索
最新留言
文章归档
网站收藏
友情链接