directory

 

Python3 is different from python2

Higher-order functions Map and Reduce

Higher-order function filter

The higher-order function is sorted

Unit testing

Unit test the function

Unit test the class

Remote Link Windows


Python3 is different from python2

Performance: Python3 is initially less efficient than Python2, but Python3 has a lot of room for optimization and is catching up in efficiency

Encoding: Python3 source code uses UTF-8 encoding to make variables more expansive

In python2 you can use <> to stand for not equal, in python3! =

Python3 adds the as and with keywords, and True, False, and None

Python2 uses the divisor (/) to round automatically, whereas Python3 uses the divisor (/) to round decimals and must use //

Python2 has the print statement, whereas Python3 has the print() function

Python3 removes raw_input and adds input()

The new super() can be passed without arguments in python3

In python2, comparisons can be performed even if the types do not match, such as 2<‘4’, which returns True. Python3 changed the behavior of the sequential operators, such as x<y, and when the types of x and y do not match, TypeError is raised instead of returning bool

Python2 strings are stored as 8-bit strings, in Python3 as 16-bit Unicode strings, and strings have only one type, STR

In python3 all exceptions are inherited from BaseException with StardardError removed

python2 :
try:...except Exception,e:
    ......

python3:
try:...except Exception as e:
    ......
Copy the code

Python2 has a built-in type file to process files. Python3 has no file class

 

Higher-order functions Map and Reduce

It was first presented in Google’s MapReduce article

Map () spreads the data out for parsing, producing a list

Reduce () data collection is processed, and this list is processed

Python has built-in map() and reduce() functions

Example: Using map()

#map()
# prototype map (fn, LSD)
#fn is a function and LSD is a sequence
Function: applies the passed function to each element of the sequence and returns the result as a new Iterator

# Convert a single character to the corresponding literal integer
def chr2int(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'.'6'.'5']
#map processed lists are lazy lists
res = map(chr2int,list1)
print(res)
Convert lazy lists to lists
print(list(res))
Copy the code

Running results:

 

Example: Simple use of Ruduce ()

from functools import reduce
#reduce(fn,lsd)
#fn is a function and LSD is a sequence
A function that operates on a sequence must take two arguments. Reduce adds the result to the next element of the sequence
#reduce(f,[a,b,c,d])
#f(f(f(a,b),c),d)

Find the sum of a sequence
list = [1.2.3.4.5.6]
# 1 + 2
#1 plus 2 plus 3
#1 + 2 + 3 + 4
#1 + 2 + 3 + 4 + 5
#1 + 2 + 3 + 4 + 5 + 6
def sum(x,y) :
    return x + y
all = reduce(sum.list)
print(all)
Copy the code

Running results:

 

Higher-order function filter

Prototype: filter (fn, LSD)

Fn is a function and LSD is a sequence

Function: filter a sequence by applying a function passed in to each element of the sequence, deciding whether to keep the element based on whether it returns True or False

Example: Keep the odd numbers in the sequence

# preserve the odd number of sequences
list1 = [1.2.3.4.5.6.7.8.9]
def isjishu(num) :
    # Even reserved
    if num%2! =0:
        return True
    # odd number
    return False
l = filter(isjishu,list1)
print(list(l))
Copy the code

Running results:

 

The higher-order function is sorted

Sort: bubble sort, select sort quicksort, insert sort, counter sort

Comparatively speaking, bubble sort, selection sort is less efficient than quicksort, insert sort, and counter sort

Sorted: Sorts sequences. When sorting strings, it compares ASCLL code values

Example:

# sort list1 = [,9,1,3,7, 4,8,6-4-8] # sorted ascending order by default list2 = sorted (list1) print (list2) # according to the list is the absolute value, the key can accept function to realize a custom collation list3 = Sorted (list1,reverse=True) print(list4)Copy the code

Running results:

 

Unit testing

Development generally requires testers.

Unit tests are used to verify the correctness of a function, class, or module

Results:

  1. Unit test. Pass, the function function is normal;
  2. If the unit test fails, the function is buggy or the input criteria are wrong

 

Unit test the function

Example: an x+y addition function test

The first time was a successful addition, and the second time the addition function was modified

import unittest
# from unit test function import function
def sum(x,y) :
    return x + y 

class Test(unittest.TestCase) :
    def setUp(self) :
        print('Automatically called when tests start')
    def tearDown(self) :
        print('Automatically called when the test ends')

    # To test sum
    def test_sum(self) :
        self.assertEqual(sum(1.2),3.'Wrong addition')

if __name__=='__main__':
    unittest.main()
Copy the code

Running results:

Modify the addition function:

def sum(x,y) :
    return x + y + 1
Copy the code

Running results:

 

Unit test the class

Start by defining a Person class

class Person(object) :
    def __init__(self,name,age) :
        self.name = name
        self.age = age

    def getAge(self) :
        return self.age
Copy the code

Test this class

import unittest
# from unit test function import function
from Person import Person

class Test(unittest.TestCase) :
    def setUp(self) :
        print('Automatically called when tests start')
    def tearDown(self) :
        print('Automatically called when the test ends')
    # To test sum
    def test_init(self) :
        per = Person('tom'.20)
        self.assertEqual(per.name,'tom'.'Attribute assignment error')
    def test_getAge(self) :
        per = Person('tom'.20)
        self.assertEqual(per.getAge(),per.age,'getAge is wrong. ')

if __name__=='__main__':
    unittest.main()
Copy the code

Running results:

 

Remote Link Windows

import telnetlib

def telnetDoSomething(IP,user,passwd,command) :
    # link server
    telnet = telnetlib.Telnet(IP)
    Set the debug level
    telnet.set_debuglevel(2)

    Read user information
    rt = telnet.read_until('Login username:'.encode('utf-8'))
    # write user name,'\r\n' is carriage return
    telnet.write((user+'\r\n').encode('utf-8'))
    Read the password information
    rt = telnet.read_until('Login password:'.encode('utf-8'))
    # write password,'\r\n' is carriage return
    telnet.write((passwd + '\r\n').encode('utf-8'))
    Read and verify IP information
    rt = telnet.read_until('Domain name:'.encode('utf-8'))
    # write IP,'\r\n' is carriage return
    telnet.write((IP + '\r\n').encode('utf-8'))

    # Login successful, write command
    rt = telnet.read_until('>'.encode('utf-8'))
    telnet.write((command + '\r\n').encode('utf-8'))
    SQL > select * from 'SQL' where 'SQL' >
    # fail, usually not >
    rt = telnet.read_until('>'.encode('utf-8'))
    # Disconnect
    telnet.close()
    return True

if __name__ == '__main__':
    IP = '10.0.142.197'
    user = 'xumingbin'
    passwd = '* * * * * * * * *'
    command = 'tasklist'
    telnetDoSomething(IP,user,passwd,command)
Copy the code

 

 

 

Learn together and make progress together. If there are any mistakes, please comment