偏函数(Partial Function)是 Python 中的一个实用工具,通常用于函数式编程中,可以固定一个函数的部分参数,从而生成一个新的函数。偏函数在 Python 中通常通过 functools.partial 实现。在面试中,考察偏函数的目的通常是测试候选人对函数式编程的理解,以及是否能灵活运用 Python 标准库中的工具解决实际问题。
以下是一些关于偏函数的面试题及其解答示例:
面试题 1
题目描述:
实现一个偏函数,该函数用于计算给定列表中所有元素的平方和。
解决方案:
from functools import partial
import functoolsdef sum_of_squares(lst):return sum(x**2 for x in lst)# 创建一个偏函数,固定函数的参数
sum_of_squares_fixed = partial(sum_of_squares, lst=[1, 2, 3, 4, 5])result = sum_of_squares_fixed()
print(result) # 输出应为 55
面试题 2
题目描述:
给定一个函数 concat_strings,该函数接受两个字符串参数并返回它们的连接结果。请使用偏函数实现一个新的函数 concat_with_hello,该函数总是将字符串 'Hello ’ 作为第一个参数。
解决方案:
from functools import partialdef concat_strings(s1, s2):return s1 + s2# 创建一个偏函数,固定第一个参数
concat_with_hello = partial(concat_strings, 'Hello ')result = concat_with_hello('World!')
print(result) # 输出应为 'Hello World!'
面试题 3
题目描述:
给定一个函数 calculate,该函数接受三个参数:操作符 (op) 和两个数值 (num1, num2),并根据操作符执行相应的数学运算。请使用偏函数实现一个新的函数 add_numbers,该函数总是执行加法操作。
解决方案:
from functools import partialdef calculate(op, num1, num2):if op == '+':return num1 + num2elif op == '-':return num1 - num2elif op == '*':return num1 * num2elif op == '/':return num1 / num2else:raise ValueError("Unsupported operator")# 创建一个偏函数,固定操作符为 '+'
add_numbers = partial(calculate, '+')result = add_numbers(10, 5)
print(result) # 输出应为 15
面试题 4
题目描述:
编写一个偏函数,该函数用于计算一个数的幂。请使用偏函数创建一个新的函数 square,该函数总是计算一个数的平方。
解决方案:
from functools import partialdef power(base, exponent):return base ** exponent# 创建一个偏函数,固定指数为 2
square = partial(power, exponent=2)result = square(5)
print(result) # 输出应为 25
面试题 5
题目描述:
给定一个函数 format_string,该函数接受一个字符串和一个格式字符串,返回格式化后的字符串。请使用偏函数实现一个新的函数 format_with_percent,该函数总是使用 %s 格式化字符串。
解决方案:
from functools import partialdef format_string(fmt, value):return fmt % value# 创建一个偏函数,固定格式字符串为 '%s'
format_with_percent = partial(format_string, '%s')result = format_with_percent('hello')
print(result) # 输出应为 'hello'