HOME: Count Digits —— 計算字串中數字個數

胡奚發表於2020-12-18

CheckIO是一個通過闖關遊戲學習程式設計的網站(Python和JavaScript)。通過解題開發新“島嶼”,同時,通過做任務獲得Quest Points解鎖會員題目。
文章內容:題目、我自己的思路和程式碼以及優秀程式碼,如果想看大神解題可以直接跳到“優秀程式碼”部分。
本題連結:https://py.checkio.org/en/mission/count-digits/

題目

計算字串中數字的個數。

輸入: 字串
輸出: 整數

舉個例子:

count_digits('hi') == 0
count_digits('who is 1st here') == 1
count_digits('my numbers is 2') == 1
count_digits('This picture is an oil on canvas '
 'painting by Danish artist Anna '
 'Petersen between 1845 and 1910 year') == 8
count_digits('5 plus 6 is') == 2
count_digits('') == 0

難度: Elementary

題目框架

def count_digits(text: str) -> int:
    # your code here
    return 0

if __name__ == '__main__':
    print("Example:")
    print(count_digits('hi'))

    # These "asserts" are used for self-checking and not for an auto-testing
    assert count_digits('hi') == 0
    assert count_digits('who is 1st here') == 1
    assert count_digits('my numbers is 2') == 1
    assert count_digits('This picture is an oil on canvas '
 'painting by Danish artist Anna '
 'Petersen between 1845 and 1910 year') == 8
    assert count_digits('5 plus 6 is') == 2
    assert count_digits('') == 0
    print("Coding complete? Click 'Check' to earn cool rewards!")

思路及程式碼

思路

  • 依次判斷字串中元素是否是數字型別
    (這個題和 Sum Numbers 題類似

程式碼

def count_digits(text: str) -> int:
    count = 0
    for i in text:
        if i.isdigit():
            count += 1
    return count

優秀程式碼

No.1

def count_digits(text: str) -> int:
    return sum(c.isdigit() for c in text)

No.2

def count_digits(text: str) -> int:
    return sum(map(str.isdigit, text))

No.3

def count_digits(text:str)->int:
	return len([x for x in text if x.isdigit()])

相關文章