【Python CheckiO 题解】All the Same
生活随笔
收集整理的這篇文章主要介紹了
【Python CheckiO 题解】All the Same
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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
題目描述
【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() 函數刪除重復數據,如果其長度小于等于1,返回 True,否則返回 False。
代碼實現
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])總結
以上是生活随笔為你收集整理的【Python CheckiO 题解】All the Same的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: REVERSE-PRACTICE-BUU
- 下一篇: 【Python 必会技巧】使用 join