Today's lessons are as follows:
1. In C/C++, the result of the'/ 'arithmetic operator is usually determined by the data on both sides of the operation, such as: 6/3 = 2; 6,3 are integers, so the result is integer 2; 6.0 / 3.0 = 2.0; 6.0, 3.0 is a floating point number, so the result is also floating point 2.0, which is precisely Python 2.2 as long as one number on both sides of'/'Is a floating point number.This was the same before, but Python designers thought it didn't conform to Python's simplicity and added an arithmetic operator'// 'to Python 2.2 and later to represent integer division, returning the largest integer not larger than the result, and'/' simply represents floating-point division, but in order to compromise, all 2In the.X version, also for backward compatibility, if you want to use'//', you must add a statement:'/ 'denotes a floating-point division and returns a floating-point result when you see this sentence from u future_u import divisio;'//' denotes an integer division.However, this compromise is not expected when Python 3.0 is released, "/" must represent a floating-point division and return a floating-point result; "//" represents an integer division
2. Review Progress Bar
import time for i in range(0,101,2): time.sleep(0.1) char_num = i//2 per_str = '\r%s%% : %s\n' %(i, '*' * char_num)\ #here\The effect is that the string is too long to wrap if i == 100 else '\r%s%% :%s' %(i,'*'*char_num)# print(per_str,end ='',flush = True) print(123) # for i in range(10): # # s = 'ss%s\r'%i # print(s,end = '')
3. Built-in functions
# exec('print(123)') # eval('print(123)') # print(eval('1+2+3'))# Has a return value of 6 # print(exec('1+2+3'))#no return value None # exec and eval Can execute code of string type # eval Return Value - Simple calculation with results # exec No return value - simple process control # eval Only if you know exactly what code you want to execute # code = '''for i in range(10): # print(i*'*')''' # exec(code) # code = 'for i in range(10):print(i)' # # compilel = compile(code,'','exec') # # exec(compile) # exec(code) # code = '1 + 2 + 3' # compile2 = compile(code,'','eval') # print(eval(compile2)) # eval(compile2) # print(eval(code)) # # name #After execution name Variable has value # "'pythoner'" # Complex number- complex # Real number: rational number # Irrational Number # Imaginary number: Imaginary number # 5 + 12j === Compound number === complex # 6 + 15j # Floating point number (finite cyclic decimal, infinite cyclic decimal) != Decimals: finite cyclic decimals, infinite cyclic decimals, infinite non-cyclic decimals # Floating point number #354.123 = 3.54123*10**2 = 35.4123 * 10 # f = 1.781326913750135970 # print(f) # print(bin(10)) # print(oct(10)) # print(hex(10)) # print(abs(-3)) # print(divmod(2,3))# div division mod Remaining # print(divmod(3,5)) # print(round(2.4545)) # print(round(2.8546655444,5)) # print(pow(2,5)) # print(pow(5,4)) # print(pow(1,4,1)) # print(pow(2,4,2))#Divide the first two power operations by three numbers to make the remainder # ret = sum([1,2,3,4,5,6],10) # print(ret) print(min(1,2,3,4)) print(min(1,2,3,4,-3)) print(min(1,2,3,4,-3,key = abs)) print(min([1,2,3,4])) print(max(1,2,3,4)) print(max(1,2,3,4,-3)) print(max(1,2,3,4,-3,key = abs)) print(max([1,2,3,4]))
# list = [1,2,3] # l = list.reverse() # print(l) # # print(list) # list = [1,2,3] # l = reversed(list) # print(l) # print(l.__next__()) # l = [1,2,3,4,4,5,8] # s = slice(1,7,2) # print(s) # print(l[s]) # print(l[1:7:2]) # print(format('test', '<10')) # print(format('test', '>40')) # print(format('test', '^40')) # Network programming can only pass binary # Photos and videos are also stored in binary # html Web pages crawl to codes, too # b_array = bytearray('Hello',encoding = 'utf-8') # print(b_array) # print(b_array[0]) # b_array[1]=255 # print(b_array) # print(ord('a')) # print(ord('1')) # print(chr(97)) # print(ord('good')) print(repr(1)) print(str(1)) print(repr('1')) print(str('1')) name = 'egg' print('Hello%r'%name) name = 'egg' print('Hello%s'%name)
# print(all(['a','','e'])) # print(all(['a','e'])) # print(all(['','e'])) # # print(any(['a','','e'])) # print(any(['a','e'])) # print(any([0,'e'])) # # l = [1,2,3,4] # s = [1,2,3,4] # m = [1,2,3,[4,5]] # n = {1:2,3:4} # for i in zip(l,s,m,n): # print(i) # # def func(x): # # return x % 2 == 1 # if x > 10: # return x # ret = filter(func,[1,23,4,5]) # print(ret) # for i in ret: # print(i) # def is_not_empty(s): # return s and len(s.strip()) > 0 # ret = filter(is_not_empty, ['test', None, '', 'str', ' ', 'END']) # print(ret) # for i in ret: # print(i) # filter Executed filter Later result set <= Number before execution #filter Filtering alone will not change the original value # map Number of elements unchanged before and after execution # Value may change # from math import sqrt # def func(num): # res = sqrt(num) # return res % 1 == 0 # ret = filter(func,range(1,101)) # for i in ret: # print(i) # ret = map(abs,[12,-3,4,5]) # print(ret) # for i in ret: # print(i) # l = [1,23,4,-5,-6,6] # # print(l.sort(key = abs)) # Sort on the original list # # print(l) # # print(sorted(l,key = abs,reverse = True))# A new list was generated without changing the memory footprint of the original list # print(l) l = [' ', '2','34','dfsdsdffsd'] print(sorted(l,key = len))
4. Anonymous functions
# def add(x,y): # return x+y # add = lambda x,y:x+y # print(add(1,2)) # # dic = {'key1':1,'key2':20,'key3':3} # print(max(dic,key = lambda a:dic[a])) #Two exercises # 1.The output of the following program is: # d = lambda p:p*2 # t = lambda p:p*3 # x = 2 # x = d(x) # x = t(x) # x = d(x) # print(x) # 2.Existing Bituples(('a'),('b')),(('c'),('d')),Please use python List generated by anonymous functions in[{'a':'c'},{'b':'d'}] # ret = zip(('a','b'),(('c'),('d'))) # # def func(x): # # return {x[0]:x[1]} # res = map(lambda x:{x[0]:x[1]},ret) # # for i in ret: # # print(i) # print(list(res)) # 3.What is the output of the following code?Please give an answer and explain. # def multipliers(): # return [lambda x:i*x for i in range(4)] # print([m(2) for m in multipliers()]) # Please modify multipliers Definition to produce the desired result. def func(): return 'ss'*i for i in range(4): func() print(func()) # def multipliers(): # return [lambda x:0*x,lambda x:1*x,lambda x:2*x,lambda x:3*x] # print([m(2) for m in lambda x:0*x,lambda x:1*x,lambda x:2*x,lambda x:3*x]) # dic={'k1':10,'k2':100,'k3':30} # def func(key): # return dic[key] # print(max(dic,key=func)) #The maximum value is determined from the return value, and the parameter with the largest return value is the result # print(max(dic,key=lambda key:dic[key])) # max([1,2,3,4,5,-6,-7],key=abs) # ret = map(abs,[-1,2,-3,4]) # for i in ret: # print(i) # def func(x): # return x**2 # ret = map(func,[-1,2,-3,4]) # for i in ret: # print(i) # # ret = map(lambda x:x**2,[-1,2,-3,4]) # def func(x): # return x>10 # # res = filter(func,[5,8,11,9,15]) # for i in res: # print(i) # min max filter map sorted - lambda # d = lambda p:p*2 # t = lambda p:p*3 # x = 2 # x = d(x) #x = 4 # x = t(x) #x = 12 # x = d(x) #x = 24 # print(x) # ret = zip((('a'),('b')),(('c'),('d'))) # ret = map(lambda t:{t[0]:t[1]},ret) # print(list(ret)) #Existing Bituples(('a'),('b')),(('c'),('d')), # Please use python List generated by anonymous functions in[{'a':'c'},{'b':'d'}] # max min sorted filter map # Anonymous function == Built-in function # zip # ret = zip((('a'),('b')),(('c'),('d'))) # res = map(lambda tup:{tup[0]:tup[1]},ret) # print(list(res)) # def multipliers(): # return [lambda x:i*x for i in range(4)] # print([m(2) for m in multipliers()])
5. Exercises
# 3.use map To process a list of strings,Make everyone on the list sb,Example alex_sb name=['alex','wupeiqi','yuanhao','nezha'] # def func(item): # return item+'_sb' # ret = map(func,name) #ret Is Iterator # for i in ret: # print(i) # print(list(ret)) # ret = map(lambda item:item+'_sb',name) # print(list(ret)) # 4.use filter Function handles a list of numbers, filtering out all even numbers in the list # num = [1,3,5,6,7,8] # def func(x): # if x%2 == 0: # return True # ret = filter(func,num) #ret Is Iterator # print(list(ret)) # # ret = filter(lambda x:x%2 == 0,num) # ret = filter(lambda x:True if x%2 == 0 else False,num) # print(list(ret)) # 5.Write a file of more than 20 lines at random # Run the program, read the contents into memory, and store them in a list. # Receive user input page number, 5 bars per page, output only the content of the page # with open('file',encoding='utf-8') as f: # l = f.readlines() # page_num = int(input('Please enter a page number: ')) # pages,mod = divmod(len(l),5) #Find out how many pages there are and if there are any remaining rows # if mod: # If there are any remaining rows, add one to the number of pages # pages += 1 # How many pages in total # if page_num > pages or page_num <= 0: #User-entered pages greater than total or less than or equal to 0 # print('Input Error') # elif page_num == pages and mod !=0: #If the page number entered by the user is the last page and there have been remaining rows before # for i in range(mod): # print(l[(page_num-1)*5 +i].strip()) #Output only the remaining lines on this page # else: # for i in range(5): # print(l[(page_num-1)*5 +i].strip()) #Output 5 lines # 6.As follows, for each small dictionary name Corresponding to the stock name, shares How many shares do you have? price Price of corresponding stock # portfolio = [ # {'name': 'IBM', 'shares': 100, 'price': 91.1}, # {'name': 'AAPL', 'shares': 50, 'price': 543.22}, # {'name': 'FB', 'shares': 200, 'price': 21.09}, # {'name': 'HPQ', 'shares': 35, 'price': 31.75}, # {'name': 'YHOO', 'shares': 45, 'price': 16.35}, # {'name': 'ACME', 'shares': 75, 'price': 115.65} # ] # 6.1.Calculate the total price of each stock purchased # ret = map(lambda dic : {dic['name']:round(dic['shares']*dic['price'],2)},portfolio) # print(list(ret)) # 6.2.use filter Filter out which stocks have a unit price greater than 100 # ret = filter(lambda dic:True if dic['price'] > 100 else False,portfolio) # print(list(ret)) # ret = filter(lambda dic:dic['price'] > 100,portfolio) # print(list(ret))
6. Recursive Functions
Initial Recursion
Recursive Definition - Calling the function itself in a function
Now we have a general idea of what the story function just talked about does, which is to call the function itself in a function. This magical way of using functions is called recursion.
We have just written one of the simplest recursive functions.
def story(): print('sdf') story() story()
Maximum depth of recursion - 997
As you've just seen, recursive functions continue to be executed without being blocked by external forces.But as we've said before about function calls, each function call has its own namespace, which can cause too much memory to be used if it's called all the time. To eliminate this, python forced the recursive hierarchy to be controlled at 997
This way we can modify the maximum depth of recursion
import sys sys.setrecursionlimit(500) def foo(n): print(n) n += 1 foo(n) foo(1)
7. Binary Search Algorithm
#The algorithms we learn are all in the past
#Understanding the basic algorithms will create better ones
#Not everything can be solved in a ready-made way
#Sometimes you use the algorithmic knowledge you've learned to solve new problems
The #binary search algorithm must process an ordered list
# l = [2,3,5,10,15,16,18,22,26,30,32,35,41,42,43,55,56,66,67,69,72,76,82,83,88]
# 5000000 4999998
#Code implementation
Simple version dichotomy# Binary lookup algorithms must process ordered lists l = [1,2,3,4,5,6,7,8,9,10] def find(l,aim): mid_index = len(l)//2 if l[mid_index] < aim: new_1 = l[mid_index+1 :] find(new_1,aim) elif l[mid_index] > aim: new_1 = l[:mid_index] find(new_1,aim) else: print('Eureka',mid_index,l[mid_index]) find(l,4)