Python anonymous functions lambda and switch implementation, pythonlambda

Source: Internet
Author: User

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)

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.