Python functional Programming-higher-order function map, Reduce, Filter, Sorted

Source: Internet
Author: User
Tags iterable

1.1   Higher order functions

Variables can point to functions

>>> ABS (-10)

10

>>> x = ABS--x points to abs function

>>> x ( -1)-- call X directly

1

Call ABS and call x exactly the same.

The function name is also a variable

>>> ABS = 10

>>> ABS (-10)

Traceback (most recent):

File "<stdin>", line 1, in <module>

TypeError: ' int ' object is not callable

Incoming function (higher order function)

A variable can point to a function, which can receive a variable, and a function can receive another function as a parameter, a function called a higher order function.

In short: for example >>> ABS (ABS ( -10)), this is a high-order function

>>> def add_abs (x, Y, f):

... return f (x) + f (Y)

...

>>>

>>> Add_abs ( -1,-2, ABS)

3

1.1.1   Map/reduce

Both the Map and the Reduce functions are built-in functions of Python.

1.1.1.1  Map

The map () function receives two parameters, one is a function , the other is a iterable, andthe map functions the incoming function sequentially to each element of the sequence. and return the result as a new Iterator .

>>> def f (x):

... return x * x

...

>>>

>>> R =map (f, [1, 2, 3, 4, 5, 6])

>>> Print (R)

<map Object at 0x2b9993f1bb00>

>>> list (r)

[1, 4, 9, 16, 25, 36]

>>> list (Map (str,[1, 2, 3, 5,7))-- convert to String

[' 1 ', ' 2 ', ' 3 ', ' 5 ', ' 7 ']

1.1.1.2  Reduce

Reduce functions a function in a sequence [x1, x2,x3, ...] , the function must receive two parameters,and reduce calculates the result and the next element of the sequence, and the effect is:

Reduce (f, [X1, x2, X3, x4]) = f (f (f (x1,x2), x3), x4)

Simple implementation of the sum function

>>> fromfunctools Import reduce

>>> def add (x, y):

... return x + y

...

>>> Reduce (add,[1, 3, 5, 7, 9])

25

Furthermore, Turn 1, 3, 5, 7, 9 into 13579

>>> from functools Import reduce

>>> def fn (x, y):

... return x * ten + y

...

>>> Reduce (fn,[1, 3, 5, 7, 9])

13579

implement int function, convert "13579" to 13579

>>> from functools Import reduce

>>> def strtoint (s):

... def fn (x, y):

... return x * ten + y

... def chartonum (s):

... return {' 0 ': 0, ' 1 ': 1, ' 2 ': 2, ' 3 ': 3, ' 4 ': 4, ' 5 ': 5, ' 6 ': 6, ' 7 ': 7, ' 8 ': 9}[s] #dict[key],whe n s= ' 0 ' then return 0

... return reduce (FN, map (Chartonum, s))

...

>>>

>>>

>>> strtoint (' 9102384 ')

9102384

1.1.2   Filter

like map () ,filter () also receives a function and a sequence. unlike map () ,filter () applies the incoming function to each element sequentially, and then decides whether to persist or discard the element based on whether the return value is True or False.

>>> def is_odd (n):

... return n% 2 = = 1

...

>>>

>>>

>>> List (filter (is_odd, [1, 2, 3, 4, 5]))

[1, 3, 5]

Notice that the filter () function returns a Iterator, which isan inert sequence , so forcing the filter () To complete the calculation, you need to use the list () function to get all the results and return to the list.

To delete an empty string from a sequence

>>> def no_empty (s):

... return s and S.strip ()

...

>>>

>>> List (filter (No_empty, [' A ', None, ' ', ' C ')])

[' A ', ' C ']

Similarly delete spaces in a string

>>> List (Filter (No_empty, (' AC)))--' A C ' is a iterable

[' A ', ' C ']

with the filter seeking primes

One way to calculate prime numbers is through the method of the Fourier sieve, which is very simple to understand:

First, List all the natural numbers starting with 2, and construct a sequence:

2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...

take the first number of the sequence 2, it must be a prime, and then sift out the multiples of 2 of the sequence with 2:

3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...

take the first number of a new sequence of 3, it must be a prime, and then sift out the multiples of 3 of the sequence 3:

5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...

take the first number of the new sequence 5, and then sift out the multiples of 5 of the sequence with 5:

7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...

Keep sifting down and you can get all the primes.

1. this is calculated directly from the odd sequence, defining an odd series generator

>>> def _odd_iter ():

... n = 1

... while True:

... n = n + 2

... yield n

2. remove the irreducible from the odd sequence and define a non-out function for filtering

>>> def _not_divisible (n):

... return lambda x:x% n > 0

3. Generating a sequence of prime numbers with filter

>>> def prims ():

... yield 2

... it = _odd_iter () # the first odd sequence 3,5,7,9,11,13

... while True:

... n = next (IT) # first time with 3 for non-removable function filtering

... it = filter (_not_divisible (n), it) # a new odd sequence formed:3,5,7,11,13,17, naturally the second time brought into 5 for non-removable filtering.

4. try to generate

>>> for N in Prims ():

... if n < 100:

... print (n)

.. else:

... break

...

2

3

5

7

11

13

17

19

23

29

31

37

41

43

47

53

59

61

67

71

73

79

83

89

97

1.1.3   Sorted

A simple sort operation

>>> Sorted ((1,-2, 3, 5))

[-2, 1, 3, 5]

Sorted It 's also a high-order function

>>> sorted ([ -18,1,3,-7], key =abs)-- Sort by absolute size

[1, 3,-7,-18]

Ordering of strings - key is keys

>>> sorted ([' Bob ', ' about ', ' Zoo ', ' credits '])

[' Credits ', ' Zoo ', ' about ', ' Bob ']

by default, follow The size of the ASCII comparison

>>> sorted ([' Bob ', ' about ', ' Zoo ', ' credits '], key = str.lower)--Convert to lowercase in comparison

[' About ', ' Bob ', ' credits ', ' Zoo ']

Reverse Sort

>>> sorted ([' Bob ', ' about ', ' Zoo ', ' credits '], key = str.lower, reverse = True)

[' Zoo ', ' credits ', ' Bob ', ' about ']


This article is from the "90SirDB" blog, be sure to keep this source http://90sirdb.blog.51cto.com/8713279/1820871

Python functional Programming-higher-order function map, Reduce, Filter, Sorted

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.