再简单的代码也要亲手敲一遍
Topic source>>> def same(x, *fs):
... s = ['error' if (f == sqrt) and (x < 0) or (f == abs) and (x > 0) else f(x) for f in fs]
... return s
...
借用你的代码,针对输入错误进行判断,然后输出错误
你这个不对,存在Bug,我们都知道,求一个正数的绝对值是没有意义的,那么问题也就来了,你这个方法传递一个负数作为参数就不行了,因为在sqrt方法求值时就出错了,一个负数是没有平方根的...
代码优化如下:
#!/usr/bin/python
# -*- coding: utf-8 -*-
# 引入数学模块中的方法
from math import sqrt
from math import tan
'''
高阶函数应用,返回一个数字不同方法计算结果
'''
def same(num, *kw):
# 参数检查
if not isinstance(num, (int, float)):
raise TypeError('bad operand type')
# 初始化结果字典
rel = {}
# 循环计算可变参数
for func in kw:
try:
rel[str(func)[str(func).find('function ') + 9: -1]] = func(num)
except ValueError:
rel[str(func)[str(func).find('function ') + 9: -1]] = 'None'
# 返回结果字典
return rel
# 函数调用
result = same(-10.5, sqrt, abs, tan)
# 结果输出
print result
{'tan': -1.8498999934219273, 'abs': 10.5, 'sqrt': 'None'}
def do_sth(x=[],*func): return [f(x_k) for x_k in x for f in func] print(do_sth([1,2,4,9],abs,sqrt))
for x_k in x 和for f in func位置互换不影响结果吗?
def same(x, *fs):
s = [f(x) for f in fs]
return s
def f1(a):
return a+1
def f2(b):
return b+2
print(same(2,f1,f2))
试了一下,函数个数可变,只要定义的函数参数数目类型一致,且实际传入函数参数的数目和类型也满足要求即可。
不需要参数个数和函数个数一样,只要像这样修改下
from math import sqrt
from math import tan
def func(x=[],*fs):
return [[f(x1) for f in fs] for x1 in x]
print(func([5,6,7,8,9],sqrt,abs,tan))
少年丶喝酒不
这个确实可以,函数参数要相同