【Python CheckiO 题解】Digits Multiplication
CheckiO 是面向初學者和高級程序員的編碼游戲,使用 Python 和 JavaScript 解決棘手的挑戰(zhàn)和有趣的任務,從而提高你的編碼技能,本博客主要記錄自己用 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
題目描述
【Digits Multiplication】:給你一個正整數,請你寫一個函數來實現:將正整數的每一位(不包括0)相乘,例如:給你 123405, 你應該這樣處理 1*2*3*4*5=120(別忘了把0丟掉)。
【鏈接】:https://py.checkio.org/mission/digits-multiplication/
【輸入】:一個正整數
【輸出】:正整數的每一位相乘后的結果
【范例】:
checkio(123405) == 120 checkio(999) == 729 checkio(1000) == 1 checkio(1111) == 1解題思路
先將給的整數轉換成字符串形式,循環(huán)訪問該字符串,如果值不為 0,就將該字符轉化成整型,然后依次相乘即可。
代碼實現
def checkio(number: int) -> int:num = 1for i in str(number):if i != '0':num *= int(i)return numif __name__ == '__main__':print('Example:')print(checkio(123405))# These "asserts" using only for self-checking and not necessary for auto-testingassert checkio(123405) == 120assert checkio(999) == 729assert checkio(1000) == 1assert checkio(1111) == 1print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")大神解答
大神解答 NO.1
def checkio(number: int) -> int:if 0 < number < 10 ** 6:result = 1for n in str(number): if n != '0':result = result * int(n)return result大神解答 NO.2
from functools import reducedef checkio(number: int) -> int:return reduce(lambda x,y: x*y, [int(i) for i in str(number).replace('0','')])大神解答 NO.3
def checkio(number: int) -> int:r = 1while number:number, n = divmod(number, 10)if n: r *= nreturn r總結
以上是生活随笔為你收集整理的【Python CheckiO 题解】Digits Multiplication的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 59元 小米有品众筹多功能香氛随身风扇:
- 下一篇: 10年后有望取代iPhone 苹果AR眼