【Python CheckiO 题解】All the Same
CheckiO 是面向初學(xué)者和高級程序員的編碼游戲,使用 Python 和 JavaScript 解決棘手的挑戰(zhàn)和有趣的任務(wù),從而提高你的編碼技能,本博客主要記錄自己用 Python 在闖關(guān)時(shí)的做題思路和實(shí)現(xiàn)代碼,同時(shí)也學(xué)習(xí)學(xué)習(xí)其他大神寫的代碼。
CheckiO 官網(wǎng):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
題目描述
【All the Same】:檢查給定的列表,判斷是否其中所有的元素都相等
【鏈接】:https://py.checkio.org/mission/all-the-same/
【輸入】:列表(List)
【輸出】:布爾值(Bool),True 或者 False
【范例】:
all_the_same([1, 1, 1]) == True all_the_same([1, 2, 1]) == False all_the_same(['a', 'a', 'a']) == True all_the_same([]) == True解題思路
利用 set() 函數(shù)刪除重復(fù)數(shù)據(jù),如果其長度小于等于1,返回 True,否則返回 False。
代碼實(shí)現(xiàn)
from typing import List, Anydef all_the_same(elements: List[Any]) -> bool:if len(set(elements)) <= 1:return Trueelse:return Falseif __name__ == '__main__':print("Example:")print(all_the_same([1, 1, 1]))# These "asserts" are used for self-checking and not for an auto-testingassert all_the_same([1, 1, 1]) == Trueassert all_the_same([1, 2, 1]) == Falseassert all_the_same(['a', 'a', 'a']) == Trueassert all_the_same([]) == Trueassert all_the_same([1]) == Trueprint("Coding complete? Click 'Check' to earn cool rewards!")大神解答
大神解答 NO.1
def all_the_same(elements):return elements[1:] == elements[:-1]大神解答 NO.2
def all_the_same(elements):return len(elements) < 1 or len(elements) == elements.count(elementse[0])總結(jié)
以上是生活随笔為你收集整理的【Python CheckiO 题解】All the Same的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: REVERSE-PRACTICE-BUU
- 下一篇: iOS 16 Beta 2新增流量备份i