Problem 6: Filter Digits (100pts)
Problem
In this problem, you will define a higher-order function
filter_digitsthat filters the digits of a number based on a predicate function.The
filter_digitsfunction should take two arguments:
- A predicate function
fthat takes a digit and returnsTrueorFalse(whether the digit satisfies the condition).- A number
n(which can be considered as a sequence of digits).The function
filter_digits(f, n)should return a new number formed by the digits fromnfor which the predicatefreturnsTrue. The new number should contain only the digits that satisfy the predicate condition, in the same order they appear inn.
在本问题中,您将定义一个高阶函数 filter_digits,它根据一个谓词函数来过滤一个数字的各位数字。
filter_digits 函数应该接受两个参数:
- 一个谓词函数
f,它接受一个数字位(digit)作为参数并返回True或False(表示该数字位是否满足条件)。 - 一个数字
n(可以将其视为一个数字位序列)。
函数 filter_digits(f, n) 应该返回一个新数字,该数字由 n 中满足谓词 f 返回 True 的那些数字位组成。新数字应该只包含满足谓词条件的数字位,并且顺序应与它们在 n 中出现的顺序相同。
def filter_digits(f, n):
"""Return a number formed by digits from `n` that satisfy the predicate `f`.
>>> filter_digits(is_even, 123456)
246
>>> filter_digits(greater_than_three, 12345678)
45678
"""
"*** YOUR CODE HERE ***"
Hints
Hint: If no digits in n satisfy the predicate f, you should just return 0.
-
如果 \(n\) 中没有数字位满足谓词 \(f\),您应该返回 0。
-
str可以通过 OJ。
Solutions
使用 while 循环获取每位数字,然后判断是否满足条件
def filter_digits(f, n):
result = 0 # 存储最终的过滤结果
power_of_10 = 1 # 跟踪满足条件的数字的位值 (1, 10, 100, ...)
# 使用 while 循环逐位处理数字 n
while n > 0:
# 1. 获取 n 的最右边一位数字
last_digit = n % 10
# 2. 检查该数字是否满足条件 f
if f(last_digit):
# 如果满足条件,将它添加到 result 中
# 乘以 power_of_10 将该数字放到正确的位值上
result = last_digit * power_of_10 + result
# 更新 power_of_10 为下一个更高的位值
power_of_10 = power_of_10 * 10
# 3. 移除 n 的最右边一位数字,准备处理下一位
n = n // 10
# 循环结束后,n 为 0,result 包含了所有满足条件的数字
return result
使用 str 偷鸡,注意返回 0。
def filter_digits(f, n):
# 初始化为空字符串,便于增加新的数字
result = ""
# 遍历 n 对应字符串中的每一位
for digit in str(n):
# 判断是否满足条件
if (f(int(digit))):
# 若满足条件则拼接字符串
out += digit
# 注意返回 0,注意转换回 int
return 0 if result == "" else int(out)