【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") == 3 second_index("find the river", "e") == 12 second_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)總結
以上是生活随笔為你收集整理的【Python CheckiO 题解】Second Index的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 一架麦道-82客机迫降后起火:曾发生多起
- 下一篇: zookeeper集群自动启动-关闭-查