Python High-order function--map/reduce

Source: Internet
Author: User

This content I refer to Liaoche's blog, excerpt from some of the content, with a solution to his final problem code.

  1. This is the grammar I have never seen in C + + (maybe I didn't know it) and it took me ten or 20 minutes to understand it. It provides a link to Google's paper: "Mapreduce:simplified Data processing on Large Clusters", is said to be a very good article. When I understood the concept, I felt it was really convenient.
  2. Look at map first.map()The function receives two parameters, one is a function and the other isIterablemapFunctions the passed-in function sequentially to each element of the sequence and takes the result as a newIteratorReturn.

    For example, we have a function f (x) =x2, to function on a list [1, 2, 3, 4, 5, 6, 7, 8, 9] , it can be map() implemented as follows:

                f(x) = x * x                  │                  │  ┌────────────--------───┐  │   │   │   │   │   │   │   │   │  ▼   ▼   ▼   ▼   ▼   ▼   ▼   ▼   ▼[ 1    2    3    4    5    6    7    8    9 ]  │   │   │   │   │   │   │   │   │  │   │   │   │   │   │   │   │   │  ▼   ▼   ▼   ▼   ▼   ▼   ▼   ▼   ▼[ 1    4    9   16    25   36   49   64   81 ]

    Now, we use Python code to implement:

    1 def f (x): 2 ...     return x * x3 ... 4 >>> r = map (f, [1, 2, 3, 4, 5, 6, 7, 8, 9])5 >>> list (r)
         
          6 [1, 4, 9, 16, 25, 36, 49, 64, 81]
         

    map()The first parameter passed in is the f function object itself. Since the result r is one Iterator , it is an Iterator inert sequence, so the list() function allows it to calculate the entire sequence and return a list.

  3. Look againreduceThe usage.reduceA function that acts on a sequence[x1, x2, x3, ...], this function must receive two parameters,reduceThe result continues and the next element of the sequence is accumulated, and the effect is:
    reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)

    For example, to sum a sequence, it can be implemented with reduce:
     from Import Reduce def Add (x, y): ...      return x + y ... >>> reduce (add, [1, 3, 5, 7, 9])25

    This example is not very useful in itself, but if we consider that the string str is also a sequence, with a slight change to the above example, map() we can write the str converted int function:

    >>> fromFunctoolsImportReduce>>>deffn (x, y): ...returnX * 10 +y ...>>>defChar2num (s): ... digits= {'0': 0,'1': 1,'2': 2,'3': 3,'4': 4,'5': 5,'6': 6,'7': 7,'8': 8,'9'8 {}...     returnDigits[s] ...>>> reduce (FN, map (Char2num,'13579'))13579

  4. Practice
    1. Usemap()function, the user entered an irregular English name, into the first letter uppercase, other lowercase canonical name. Input:[‘adam‘, ‘LISA‘, ‘barT‘]Output:[‘Adam‘, ‘Lisa‘, ‘Bart‘]
      # -*-coding:utf-8-*- def Normalize (name):     return name.capitalize () # Test: L1 = ['Adam'LISA'BarT '  = List (map (normalize, L1))print(L2)

    2. Python provides thesum()function can accept a list and sum, write aprod()function, you can accept a list and use thereduce()Seeking Product
      #-*-coding:utf-8-*- fromFunctoolsImportReducedefprod (L):deffn (x, y):returnx*yreturnreduce (fn,l)Print('3 * 5 * 7 * 9 =', prod ([3, 5, 7, 9]))ifProd ([3, 5, 7, 9]) = = 945:    Print('Test Success!')Else:    Print('Test failed!')

    3. UsemapAndreduceWrite astr2floatfunction, put the string‘123.456‘Convert to floating point123.456
      #-*-coding:utf-8-*- fromFunctoolsImportReducedefStr2float (s): DIGITS= {'0': 0,'1': 1,'2': 2,'3': 3,'4': 4,'5': 5,'6': 6,'7': 7,'8': 8,'9'8 {} POS= Len (s)-s.index (".")-1#looking for decimal digits    defChar2num (MY_STR):if(My_str! ="."):            returnDigits[my_str]deffn (x, y):ify==None:returnxElse:            return10*x+yreturnReduce (Fn,map (char2num,s))/(10**POS)Print('str2float (\ ' 123.456\ ') =', Str2float ('123.456'))ifABS (Str2float ('123.456')-123.456) < 0.00001:    Print('Test Success!')Else:    Print('Test failed!')

Python High-order function--map/reduce

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.