代码与思路
话不多说,先放代码:
# -*- coding: utf-8 -*-
"""
codewars Kata: Calculating with Functions
Created on Sun Nov 22 20:14:45 2020
@author: Pray
"""
def zero(f = None): return f(0) if callable(f) else 0
def one(f = None): return f(1) if callable(f) else 1
def two(f = None): return f(2) if callable(f) else 2
def three(f = None): return f(3) if callable(f) else 3
def four(f = None): return f(4) if callable(f) else 4
def five(f = None): return f(5) if callable(f) else 5
def six(f = None): return f(6) if callable(f) else 6
def seven(f = None): return f(7) if callable(f) else 7
def eight(f = None): return f(8) if callable(f) else 8
def nine(f = None): return f(9) if callable(f) else 9
def plus(x): return lambda y: x + y
def minus(x): return lambda y: y - x
def times(x): return lambda y: y * x
def divided_by(x): return lambda y:int(y/x)
解决这一问题主要要灵活运用lambda函数、callable函数以及函数定义中的参数可变性。
lambda函数的说明
这个问题中最大的难点在于函数的嵌套调用,利用lambda函数可以很方便地返回一个函数,从而帮助实现函数的嵌套调用。比如在这段代码中:
def plus(x): return lambda y: x + y
这里返回的是y,而由于lambda函数的作用,其实可以看作返回了一个等待输入参数y的函数f(y),lambda使得输入参数和函数结果得到了形式上的统一,因而使得代码更为简洁。
callable函数
callable函数可以用于判断某一变量是否为函数
>> print(callable(a))
>> True #当a为一个可调用的函数时
>> print(callable(b))
>> False #当b不是一个可调用的函数时
函数参数的可变性
可以在定义函数时,在参数表中对个别参数设定默认值做到参数表的可变。实例如下:
def f(a, b=0): #当函数f中的第二个参数没有输入时,b默认为0
return a + b
def zero(f = None): #函数zero可以没有参数输入
return f(0) if callable(f) else 0
#我们要定义一个函数的时候,必须要预先定义这个函数需要多少个参数
#(或者说可以接受多少个参数)。一般情况下这是没问题的,但是也有
#在定义函数的时候,不能知道参数个数的情况(想一想C语言里的printf
#函数),在Python里,带*的参数就是用来接受可变数量参数的
def funcD(a, b, *c):
print a
print b
print "length of c is: %d " % len(c)
print c
>> funcD(1,2,3,4,5,6)
>> 1
2
length of c is: 4
(3, 4, 5, 6)
关于Python中函数的参数定义和可变参数的更多内容和信息可以参考链接:
Python中函数的参数定义和可变参数