Python-Functional programming

Source: Internet
Author: User

4. Functional Programming 4.11 Advanced functions

Map receives 2 parameters, one is the function object itself, and the other is iterable

List (map (str, [1, 2, 3, 4, 5, 6, 7, 8, 9]))

# #reduce把结果继续和序列的下一个元素做累积计算

def f (x):

... return x * x

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

--------------------------------------

> From functools Import reduce

>>> def fn (x, y):

... return x * ten + y

...

>>> def char2num (s):

... return {' 0 ': 0, ' 1 ': 1, ' 2 ': 2, ' 3 ': 3, ' 4 ': 4, ' 5 ': 5, ' 6 ': 6, ' 7 ': 7, ' 8 ': 8, ' 9 ': 9}[s]

...

>>> reduce (FN, map (char2num, ' 13579 ')) #输出int 13579

--------------

Using the map () function, the nonstandard English name entered by the user becomes the first letter capitalized, and the other lowercase canonical names.

Input: [' Adam ', ' Lisa ', ' Bart '], output: [' Adam ', ' Lisa ', ' Bart ']:

def normalize (name):

Return Name[0].upper () +name[1:].lower ()

l=[' Adam ', ' LISA ', ' BarT '

List (map (normalize,l))

------------

The sum () function provided by Python can accept a list and sum, write a prod () function that accepts a list and uses the reduce () to calculate the product:

Print (' 3 * 5 * 7 * 9 = ', prod ([3, 5, 7, 9]))

From Functools import reduce

def prod (L):

def multi (x, y)

Return X*y

return reduce (multi,l)

--------------

Use map and reduce to write a str2float function that converts the string ' 123.456 ' to a floating-point number of 123.456:

#-*-Coding:utf-8-*-

From Functools import reduce

def str2float (s):

Print (' Str2float (\ ' 123.456\ ') = ', Str2float (' 123.456 '))

4.1.2 Higher order function filter:

Like map (), filter () also receives a function and a sequence. 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, 4, 5, 6, 9, 10, 15]))

The function of #结果是奇数 filter () is to sift out the qualifying elements from a sequence. Because filter () uses lazy calculations, it is only true to filter and return the next filtered element each time it takes the filter () result.

---------------------

One way to calculate prime numbers is by means of an Ed sieve.

1. Using Python to implement this algorithm, you can first construct an odd sequence starting from 3:

Def _odd_iter ():

n = 1

While True:

n = n + 2

Yield n

2. Then define a filter function:

def _not_divisible (n):

Return lambda x:x% n > 0

3. Define a generator that continually returns the next prime number: first 2

Def primes ():

Yield 2

it = _odd_iter () # Initial sequence

While True:

n = Next (IT) # returns the first number of sequences

Yield n

it = filter (_not_divisible (n), it) # constructs a new sequence

4. Since primes () is also an infinite sequence, it is called to set a condition for exiting the loop:

For n in primes ():

If n < 1000:

Print (n)

Else

Break

? The number of returns is the same number, such as 12321,909, from left to right and read from right to left. Please filter out non-return numbers using filter ():

4.1.3 Sorting algorithm sorted

Sorted ([5, -12, 9, -21], key=abs)

[5, 9, -12, -21, approx] #可以接收一个key函数来实现自定义的排序, for example, sort by absolute # value size:

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

[' About ', ' Bob ', ' credits ', ' Zoo '] #一个key函数把字符串映射为忽略大小写排序即可

#要进行反向排序, you can pass in the third parameter reverse=true without having to change the key function:

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

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

4.2 Return function

Higher-order functions can also be returned as a result in addition to the ability to accept functions as parameters

def lazy_sum (*args):

def sum ():

Ax = 0

For n in args:

AX = ax + N

return ax

return sum

#闭包: When Lazy_sum returns the function sum, the relevant parameters and variables are saved in the returned function

def count ():

FS = []

For I in range (1, 4):

def f ():

Return I*i

Fs.append (f)

Return FS

F1, F2, F3 = count ()

------------

def count ():

def f (j):

def g ():

Return j*j

Return g

FS = []

For I in range (1, 4):

Fs.append (f (i)) # f (i) is executed immediately, so the current value of I is passed in F ()

Return FS

4.3 Anonymous functions

>>> list (map (lambda x:x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9]))

[1, 4, 9, 16, 25, 36, 49, 64, 81]

-----

4.4 Decorators

-------

4.5 Partial function

int2=functool.partical (int, base=2)

Int2 (' 10010 ') #字符串转int, in turn binary

Python-Functional programming

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.