python basis of higher-order functions

Python2 and the difference python3

performance:

1.python3.x starting lower than python2.x efficiency, but python3.x have great room for optimization, efficiency is catching up

2.python3.x original code files use utf-8 by default, making the name more widely.

python3.x

>>> 中国 = 'china'
>>> print(中国)
'china'
>>> str = "我爱北京天安门"
>>> str
'我爱北京天安门'

python2.x

>>> str = "我爱北京天安门"
>>> str
'\xe6\x88\x91\xe7\x88\xb1\xe5\x8c\x97\xe4\xba\xac\xe5\xa4\xa9\xe5\xae\x89\xe9\x97\xa8'

So use python2.x when you need to add in the header file

#-*-coding:utf-8-*-
str = "我爱北京天安门"
print(str)

3.print function

print statement is gone, replaced by a print () function

python2.x in both print is equivalent to

print "fish"
print ("fish")#注意print后面有个空格

python3.x Print

print("fish")

4. division

python division in comparison with other languages ​​is very high end, there are sets of complex rules, in python division

There // and /

First of all / Division: with other similar language in python2.x the only calculates the integer part, fractional part ignored

Floating-point division will be the result of a floating point number

python2.x in the "/"

>>> 1/2
0
>>> 1.0/2.0
0.5

python3.x in the "/"

>>> 1/2
0.5

5. Abnormal

In python3.x in exception handling it is also slightly changed, in python3 we use as a keyword

#3.x
try:
    ...
except exc as var:
    ....

 #2.x
try:
    ...
except exc, var:
    ...

Higher-order functions

1.MapReduce

MapReduce is mainly used in distributed.

Big data is actually in the second half of 15 years began to fire up.

Distributed idea: a continuous string to the list of elements of type string type, which have become digital type, the use of distributed thinking [something like a person doing it slowly, but if people do ? Efficiency can be improved accordingly]. Similarly, a computer data processing slower, but if there are 100 computers at the same time processing, the efficiency will be much faster, the final processing of the data on each computer integration.

Python advantages: the built-map () and reduce () function can be used directly.

#python内置了map()和reduce()函数
'''
def myMap(func,li):
    resList = []
    for paser in li:
        res = func(paser)
        resList.append(res)
'''       
map () function

Function: a function of incoming successively to every element in the sequence, and to return the result as a new Iterator

grammar:

map(func, lsd)

1 is a function of the parameter, the parameter is a sequence of 2

#一、map()
#原型 map(func, lsd)
#将单个字符转成对应的字面量整数
def chrToint(chr):
    return {"0":0,"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9}[chr]

list1 = ["2","1","4","5"]
res = map(chrToint, list1)
#[chr2int("2"),chr2int("1"),chr2int("4"),chr2int("5")]
print(res)
print(list(res))

#将整数元素的序列,转为字符串型
#[1,2,3,4] --》[“1”,“2”,“3”,“4”]
l = map(str,[1,2,3,4])
print(list(l))

Exercise: Using the map function, the sequence of n - [1,4,9, .., n ^ 2]

reduce () function

Function: a function of acting on the sequence, this function must accept two parameters, and the reduce the result of the next element in the sequence continues to cumulative operation

Syntax: reduce (func, lsd)

1 as a function of the parameter, the parameter list 2

reduce (f, [1,2,3,4]) is equivalent to f (f (f (1,2), 3), 4), similar to the recursive

#需求,求一个序列的和
list2 = [1, 2, 3, 4]
def mySum(x,y)
    return x+y
r = reduce(mySum,list2)
print("r=",r)

Practice, the character string converted into the corresponding digital literal

#将字符串转成对应字面量数字
def strToint(str1)
    def fc(x, y):
        return x*10 + y
    def fs(chr):
        return {"0":0,"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9}[chr]
    return reduce(fc,map(fs,list(str1)))
a = strToint("12345")
print(a)
print(type(a))

#模拟map()函数
def myMap(func,li):
    resList = []
    for n in li:
        res = func(n)
        resList.append(res)
filter

Effect: the passed successively to the function of each element, and based on the return value is True or False decided to keep or discard the element [element through the filter element list certain conditions]

'''
语法:
filter(func,lsd)
参数一:函数名
参数二:序列
功能:用于过滤序列
简单理解:把传入的函数依次作用于序列红的每一个元素,根据返回的True还是False,决定是否保留该元素。
'''
#需求:将列表中的偶数筛选出来。
list1 = [1,2,3,4,5,6,7,8]
#筛选条件
def func(num):
    #保留偶数元素
    if num%2 == 0:
        return True
    #剔除奇数元素
    return False
l = filter(func,list1)
print(l)
print(list1)

Note: Use filter () the higher-order functions, key in achieving a proper "filter" function, filter () function returns an Iterator, which is a sequence of inertia, so to compel complete filter results, use list () function to get all the results and return the list.

Exercise

Demand; the penchant for "no" to weed out data

data = [[ "name", "age", "love"], [ "tom", 25, "no"], [ "hanmeimei", 26, "money"]]

sorted

Role: to achieve the sort of list.

iterable: Iteration is the type;
cmp: function used to compare to compare what is determined by the Key;
Key: perform as a keyword with an attribute or function list element, has a default value Iteration item in the collection;
Reverse: collation. reverse = True in descending or ascending order reverse = False, you have default values.
Returns: an iterator type can be sorted, and iterable same.

#排序
#第一类:冒泡 选择
#第二类:快速,插入,计数器
#注意:如果数据量小的情况下,上述两类用法的效率基本相同,但是,如果数据量大的情况下,第一类的效率很低

#1.普通排序
list1 = [4,3,5,6,1]
#默认为升序排序
list2 = sorted(list1)
print(list2)

#2.按绝对值大小排序
list3 = [4,-352,-9]
#key接受函数来实现自定义排序规则
#abs表示通过绝对值进行排序
list4 = sorted(list3, key=abs)
#利用map可以实现取绝对值之后的排序
list5 = sorted(map(abs,list3))
print(list3)
print(list4)
print(list5)

#3.降序排序
list5 = [2,1,4,5,6,7]
#通过设置reverse=True来表示反转
list6 = sorted(list5,reverse=True)
print(list5)
print(list6)

list7 = ['a','b','c','d']
list8 = sorted(list7)
print(list7)
#同样也可以实现升序排列,结果为abcd,排序依据为ASCII值
print(list8)

#自定义函数:按照字符串的长短来进行排序
def myLen(str1)return len(str1)
list7 = ['sddd','dded','et54y5','6576986oy']
#使用自定义函数,进行排序,key=函数名
list8 = sorted(list7, key = myLen)
print(list7)
print(list8)

Unit testing and documentation

unit test

Unit is used for testing a module, a class or a function to verify the correctness of the work.

1. If the unit test passes, the work proved to be correct function tests,

2. otherwise prove either a bug or an input function is not legitimate, in short, we need to fix our function function.

A function unit test

Create a python file MathFunc.py, it reads as follows:

def mySum(x,y):
    return x + y

def mySub(x,y)
    return x -y
print(mySum(1,2))

Create a python file text01.py, reads as follows:

import unittest
from MathFunc import mySum, mySub

#测试类 继承自unittest.TestCase
class Test(unittest.TestCase):
    #下面两个方法存在的意义:假设需要连接数据库,当测试完毕之后,需要断开和数据库的连接
    def setUp(self):
        print("开始测试时自动调用")

    def tearDown(self):
        print("结束时自动调用")

    #测试相应的函数
    #一般情况下,测试函数命名格式:text_需要被测试的函数名
    def test_mySum(self):
        #断言:对函数命名格式:text_需要被测试的函数名
        self.assertEqual(mySum(1,2),3,"加法有误")

    def test_mySub(self):
        self.asserEqual(mySub(2,1),1,"减法有误")

#当主程序运行的时候,开始进行单元测试
if __name__ == "__main__":
    unittest.main()

Run text01.py file, normally found, then the content MathFunc.py file may be modified in the following manner.

def mySum(x,y):
    return x + y + 1

def mySub(x, y):
    return x - y

print(mySub(1,2))

Run again text01.py file, an error message will appear.

Unit test class

Create a class file person.py, reads as follows:

class Person(object):
    #构造方法
    def __init__(self, name, age):
        #给成员变量赋值
        self.name = name
        self.age = age

    def getAge(self):
        return self.age  

Creating text02.py files, like unit testing, as follows:

import unittest
from person import person
class Test(unittest.TestCase):
    def  test_init(self):
        p = Person('hanmeimei',20)
        self.asserEqual(p.name,"hanmeimei","属性值有误")

    def test_getAge(self):
        p = Person('hanmeimei',22)
        self.assertEqual(p.getAge(),p.age,"getAge函数有误")

if __name__ = "__main__":
    unittest.mian()

Demo, run text02.py files, programs running, person.py modify the contents of the file, as follows:

class Person(object):
    #构造方法
    def __init__(self, name, age):
        #给成员变量赋值
        self.name = name
        self.age = age

    def getAge(self):
        return self.age+1  

Will again run error

Class test unit: test unit or method in nature.

Doctests

The role of the document test: can extract annotation find that the code execution

doctest module may extract the execution code comments

doctest in strict accordance with the extraction of python's interactive mode input

import doctest
def mySum(x,y):
    #第函数进行功能和使用说明
    '''
    求两个数的和
    get The sum from x and y
    :param x:firstNum
    :param y:secondNum
    :return sum
    #注意有空格
    example:
    >>>print(mySum(1,2))
    3
    '''
    return x + y
print(mySum(12))
#进行文档测试,在当前文件中进行即可
doctest.testmod()

Note: The presentation time, the main test

example:

print(mySum(1,2))

3

Published 31 original articles · won praise 4 · Views 3511

Guess you like

Origin blog.csdn.net/qq_29074261/article/details/80016841