Python anonymous functions lambda and switch implementation, pythonlambda
1. lambda syntax is similar to es6 arrow Function
>>> show=lambda x,y: x * y>>> show( 10, 20 )200
2. Recursive factorial
>>> def fab( n ):... if n == 0:... return 1... else:... return n * fab( n - 1)... >>> fab( 3 )6>>> fab( 5 )120>>> fab( 6 )720>>>
Using the reduce function, you can also perform a cumulative operation.
>>> l = range( 1, 6 )>>> l[1, 2, 3, 4, 5]>>> def f( x, y ):... return x * y... >>> reduce( f, l )120>>>
You can use lambda expressions to simplify the definition of functions.
>>> fab = lambda x, y: x * y>>> reduce( fab, [ 1, 2, 3, 4, 5, 6 ] )720>>> reduce( lambda x,y: x *y, [ 1, 2, 3, 4, 5, 6 ] )720>>>
3. The dictionary + function can be used to determine the switch branch.
If .... Else implements addition and subtraction
#!/usr/bin/python#coding:utf-8from __future__ import divisiondef add( a, b ): return a + bdef sbb( a, b ): return a - bdef mul( a, b ): return a * bdef div( a, b ): return a / bdef oper( x, o, y ): if o == '+': return add( x, y ) elif o == '-': return sbb( x, y ) elif o == '*': return mul( x, y ) elif o == '/': return div( x, y ) else: passprint oper( 10, '/', 20 )
Transform a dictionary and a function into a switch
#! /Usr/bin/python # coding: utf-8from _ future _ import divisiondef add (a, B): return a + bdef sbb (a, B ): return a-bdef mul (a, B): return a * bdef div (a, B): return a/boper = {'+': add, '-': sbb, '*': mul, '/': div} def mySwitch (o, x, y): # return outputs [o] (x, y) # outputs. get (o) is equivalent to using [0] to retrieve a return Token in the dictionary. get (o) (x, y) print mySwitch ('/', 10, 20)