Instructions for Python [map, reduce, filter] built-in functions

Keywords: C Python Lambda

notes preceding the text of a book or following the title of an article

Introduce the methods of map, reduce, and filter built-in functions in Python

1: map

map(...)
    map(function, sequence[, sequence, ...]) -> list

Execute function(item) for item in sequence, and output the result as list.

>>> map(str, range(5))           #str operation of range(5)
['0', '1', '2', '3', '4']        #Return to list
>>> def add(n):return n+n
... 
>>> map(add, range(5))           #add the range(5) items
[0, 2, 4, 6, 8]
>>> map(lambda x:x+x,range(5))   #lambda function, item + itself
[0, 2, 4, 6, 8]
>>> map(lambda x:x+1,range(10))  #lambda function, items + 1
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> map(add,'zhoujy')            
['zz', 'hh', 'oo', 'uu', 'jj', 'yy']

#If you want to input multiple sequences, you need to support functions with multiple parameters. Note that the length of each sequence must be the same, otherwise an error is reported:
>>> def add(x,y):return x+y
... 
>>> map(add,'zhoujy','Python')
['zP', 'hy', 'ot', 'uh', 'jo', 'yn']
>>> def add(x,y,z):return x+y+z
... 
>>> map(add,'zhoujy','Python','test')     #The length of 'test' is smaller than the other two
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: add() takes exactly 2 arguments (3 given)

>>> map(add,'zhoujy','Python','testop')
['zPt', 'hye', 'ots', 'uht', 'joo', 'ynp']

2: reduce

reduce(...)
    reduce(function, sequence[, initial]) -> value

Call function for item sequence iteration in sequence. The function must have 2 parameters. If there is a third parameter, it represents the initial value. You can continue to call the initial value and return a value.

>>> def add(x,y):return x+y
... 
>>> reduce(add,range(10))        #1+2+3+...+9
>>> reduce(add,range(11))        #1+2+3+...+10
>>> reduce(lambda x,y:x*y,range(1,3),5)           #lambda function, 5 is the initial value, 1 * 2 * 5
>>> reduce(lambda x,y:x*y,range(1,6))             #Factorial, 1 * 2 * 3 * 4 * 5
>>> reduce(lambda x,y:x*y,range(1,6),3)           #Initial value 3, result 3
>>> reduce(lambda x,y:x+y,[1,2,3,4,5,6])          #1+2+3+4+5+6

3: filter

filter(...)
    filter(function or None, sequence) -> list, tuple, or string

Execute function(item) for item in sequence, and the result will be True (! =Items of 0) form a List/String/Tuple (depending on the type of sequence) to return, and False exits (0) to filter.

>>> def div(n):return n%2
... 
>>> filter(div,range(5))                    #Returns the true value of the div output that is not equal to 0
[1, 3]
>>> filter(div,range(10))
[1, 3, 5, 7, 9]
>>> filter(lambda x : x%2,range(10))        #lambda function returns odd number and list
[1, 3, 5, 7, 9]
>>> filter(lambda x : not x%2,range(10))
[0, 2, 4, 6, 8]
>>> def fin(n):return n!='z'                #Filter 'z' function, return False if z appears
... 
>>> filter(fin,'zhoujy')                    #'z' filtered
'houjy'
>>> filter(lambda x : x !='z','zhoujy')     #labmda returns True
'houjy'
>>> filter(lambda x : not x=='z','zhoujy')  #Return: String
'houjy'

In the above examples, a lambda expression is used

>>> a=lambda x:x+3
>>> a(2)
5
>>> a=lambda x,y:x+y
>>> a(2,3)
5

4, map, reduce, filter

1) : realize 5! + 4! + 3! + 2! + 1!

#!/usr/bin/env python
#-*- coding:utf-8 -*-
def add_factorial(n):
    empty_list=[]           #Declare an empty list, save the results of each factorial, so that these results can be added easily
    for i in map(lambda x:x+1,range(n)):    #Use the passed in variable (n) to generate a list, and use map to make the list + 1, eg: range (5) = > [1,2,3,4,5]
        a=reduce(lambda x,y:x*y,map(lambda x:x+1,range(i)))   #Generate factorials, use map to remove 0 from the list
        empty_list.append(a)            #append the factorial result to an empty list
    return empty_list
if __name__ == '__main__':
    import sys
#2 choose 1
#(1)
    try:
        n = input("Enter a Number(int) : ")
        result=add_factorial(n)   #Incoming variable
        print reduce(lambda x,y:x+y,result)      #Sum of factorial results
    except (NameError,TypeError):
        print "That's not a Number!"
#(two)
#    result = add_factorial(int(sys.argv[1]))   #Incoming variable
#    print reduce(lambda x,y:x+y,result)      #Sum of factorial results

result:

zhoujy@zhoujy:~/desktop/Python/4$ python factorial.py
Enter a Number(int) : 1
zhoujy@zhoujy:~/desktop/Python/4$ python factorial.py
Enter a Number(int) : 2
zhoujy@zhoujy:~/desktop/Python/4$ python factorial.py
Enter a Number(int) : 3
zhoujy@zhoujy:~/desktop/Python/4$ python factorial.py
Enter a Number(int) : 4
zhoujy@zhoujy:~/desktop/Python/4$ python factorial.py
Enter a Number(int) : 5
zhoujy@zhoujy:~/desktop/Python/4$

2) : select the prime numbers within 100-200

Ideas:

Prime refers to: only 1 and its two factors, such as 2, 3, 5, 7 are prime, that is, they can be divided by 1 and itself, 1 is not prime.
For example, if a number N is prime, it depends on whether it can divide the number x (excluding itself) between [2, N], that is, whether N%X is 0, if not, it is prime.
So the algorithm we want to implement is: take a number n, remove the number X between [2, n] to get the prime number, that is: N/2, N/3 ,N/N-2,N/N-1 ===> N/range(2,N)

#!/usr/bin/env python
#-*- coding:utf-8 -*-
def is_prime(start,stop):
    stop  = stop+1     #Include values to the right of the list
    prime = filter(lambda x : not [x%i for i in range(2,x) if x%i == 0],range(start,stop))   #Take the prime number, x the number from range(start,stop)
    print prime

if __name__ == '__main__':
    try :
        start = input("Enter a start Number :")
    except :
        start = 2   #Start value default 2
    try :
        stop  = input("Enter a stop  Number :")
    except :
        stop  = 0   #Stop number, default 0, that is, no value is returned
    is_prime(start,stop)

result:

zhoujy@zhoujy:~/desktop/Python/4$ python prime.py 
Enter a start Number :
Enter a stop  Number :10
[2, 3, 5, 7]
zhoujy@zhoujy:~/desktop/Python/4$ python prime.py 
Enter a start Number :10
Enter a stop  Number :20
[11, 13, 17, 19]
zhoujy@zhoujy:~/desktop/Python/4$ python prime.py 
Enter a start Number :
Enter a stop  Number :
[]

For more introductory tutorials, please refer to( http://www.bugingcode.com/python_start/)

Posted by karassik on Thu, 30 Apr 2020 08:22:15 -0700