Q1: Num Eights
Write a recursive function num_eights
that takes a positive integer n
and returns the number of times the digit 8 appears in n
.
Important: Use recursion; the tests will fail if you use any assignment statements or loops. (You can however use function definitions if you so wish.)
def num_eights(n):
"""Returns the number of times 8 appears as a digit of n.
>>> num_eights(3)
0
>>> num_eights(8)
1
>>> num_eights(88888888)
8
>>> num_eights(2638)
1
>>> num_eights(86380)
2
>>> num_eights(12345)
0
>>> num_eights(8782089)
3
>>> from construct_check import check
>>> # ban all assignment statements
>>> check(HW_SOURCE_FILE, 'num_eights',
... ['Assign', 'AnnAssign', 'AugAssign', 'NamedExpr', 'For', 'While'])
True
"""
"*** YOUR CODE HERE ***"
Result:
首先,我在看到这个题后,想到了通过while语句对n进行分割,并对分割出来数进行if判别,如果分割出的数==8,return 1,否则return 0。并对收集的结果进行加减,得到最后的结果。
答案代码展示:
def num_eights(n):
n = int(n) # 对n进行整数定义
count = 0 # 创建一个集合,用于接收数
while n > 0:
digit = n % 10 # 进行除余切片
if digit == 8:
count += 1
n = n // 10 # 对余数进行删除
return count