Day 13 Ternary expression lists, dictionaries, set generative generators, recursive calls of expression functions, dichotomy, anonymous functions, process-oriented programming ideas

Ternary expression:
replace the double-branch if
def max(x, y):
if x> y:
return x
else:
return y
x = 11
y = 22
print(x if x> y else y)
print(“yes” if x> y else “no”)

List Comprehension
Case 1
l = []
for i in range(10):
l.append(i)
print(l)

l = [i for i in range(10)]
print(l)

案例2
l = []
for i in range(10):
if i > 5:
l.append(i)
print(l)

l = [i for i in range(10) if i > 5]
print(l)

案例3:
names = [“LXX”, “HXX”, “WXX”, “LILI”]
l = []
for i in names:
l.append(i + “_sb”)
print(l)

l = [i + “_sb” for i in names]
print(l)

案例4:
l = []
names = [“egon”, “lxx_sb”, “hxx_sb”, “wxx_sb”]
for i in names:
if “_sb” in i:
l.append(i)

print(l)

l = [i for i in names if “_sb” in i]
print(l)

方法2:
for i in names:
if i.endswith(“sb”):
l.append(i)

print(l)

l = [i for i in names if i.endswith(“sb”)]
print(l)

Dictionary generation
res = {i: i ** 2 for i in range(5)}
print(res) square of 0-4 to generate a dictionary

items = [(“k1”, 111), (“k2”, 222), (“k3”, 333)]
print(dict(items))
res = {k: v for k, v in items}

Set production
res = {i for i in range(5)}
print(res) #There is
no tuple production, tuple will automatically generate tuples after generating the list

Generator expression:
res=(i for i in range(3))
print(res)
print(next(res))
print(next(res))
print(next(res))

with open(“a.txt”, mode=“rt”, encoding=“utf-8”) as f:
res = f.read()
print(len(res))

with open(“a.txt”, mode=“rt”, encoding=“utf-8”) as f:
res = 0
for i in f:
res += len(i)
print(res)

with open("a.txt", mode="rt", encoding="utf-8") as f:
res = sum((len(i) for i in f)) #sum() means put () The
sum of all values res = sum(len(i) for i in f)
print(res)

The recursive call of
a function : call itself inside a function, the essence of all recursive calls is a cyclic process
def func():
print("func")
func()

func()

import sys
print(sys.getrecursionlimit()) # These two lines of code view the depth of recursive calls, the highest is 1000 layers

import sys
sys.getrecursionlimit() #Set the depth of the recursive call. The recursive call will end after reaching a certain depth. If the recursive call is set to a deep level, there will be a risk of memory overflow

The premise of the recursive call: the recursive call must end at a certain level
. The two stages of the recursive call:
backtracking: refers to digging a well to the next layer.
Recursion: refers to returning to the next layer.

Function table Recursion
age (5) = age (4) + 10
age (4) = age (3) + 10
age (3) = age (2) + 10
age (2) = age (1) + 10
age (1) = 18

def age(n):
if n == 1:
return 18
return age(n - 1) + 10

res = age(5)
print(res)

Case: (recursively call the list value, traverse all the values ​​of the list)
nums = [1, [2, [3, [4, [5, [6, [7]]]]]]]
def get(l):
for i in l:
if type(i) is list:
get(i)
else:
print(i)
get(nums)

Basic algorithm: dichotomy
nums = [-3, -2, 1, 2, 5, 8, 9, 65, 458, 558, 689]
find_num = 64

def find(nums, find_num):
print(nums)
if len(nums) == 0:
print(“not exists”)
return
mid_index = len(nums) // 2 # The computer starts counting at 0, len(nums )//2 The result is the computer's median index
if find_num> nums[mid_index]:
# in the right
find(nums[mid_index + 1:], find_num) # By way of segmentation, if you take the right value, take The first value has been compared, the index is directly +1
elif find_num <nums[mid_index]:
# in the left
find(nums[:mid_index], find_num)
else:
print("you got it" )

find(nums, find_num)

Anonymous function : a function without a name.
Features: use once temporarily, lambda comes with return.
lambda embodies the idea of ​​functional programming
def func():
print("func")

func ()
func ()
func ()

res = (lambda x, y: x + y) (1, 2)
print (res)

Anonymous function example (dict changes the usage of comparison parameters):
salaries = { “egon”: 3000, “tom”: 1000000, “zxx”: 1000 } print(max([1, 2, 3])) print(max( salaries.values()))





def func(k):
return salaries[k]
print(max(salaries, key=func)) #The parameters traversed are salaries, and the key is mainly to change the comparison basis, so the comparison basis becomes the function func
print(max( salaries, key=lambda k: salaries[k])) #max built-in function takes the maximum value
print(min(salaries, key=lambda k: salaries[k])) #min built-in function takes the minimum value
print(sorted(salaries, key=lambda k: salaries[k])) #sorted sorted from small to large
print(sorted(salaries, key=lambda k: salaries[k], reverse=True)) #sorted plus reverse=True becomes large To small sort

Just understand:
map : map a list into a new list
names = ["LXX", "HXX", "WXX", "LILI"]
l = [name + "_sb" for name in names]
res = map( lambda name: name + “_sb”, names) #map The beginning of the parentheses is a function, and the latter is used to pass values. Separate by commas, the latter values ​​will be passed to the former in an iterative manner Value, assign the result of the map to res, res will directly become an iterator
print(list(res))

filter
names = ["lxx_sb", "egon", "wxx_sb", "lili_sb"]
print([name for name in names if name.endswith("sb")])
res = filter(lambda name: name.endswith( "Sb"), names) #filiter will leave the result with the Boolean value of True, and assign the result of the filter to res, and res will directly become an iterator
print(list(res))

reduce
from functools import reduce
res = reduce(lambda x, y: x + y, [1,2,3]) # reduce will combine all values ​​into one value
res = reduce(lambda x, y: x + y, ["Aa", "bb", "cc"]) # reduce will combine all values ​​into one value
print(res)
pow
res = pow(10, 2, 3) # 10**2% 3
print(res) )

Process
-oriented programming Process -oriented programming: the
core is the word "process", the process is the steps to solve the problem, that is: what to do first, then what to do.
So writing a program based on this idea is like designing a pipeline.
Advantages: complex problem flow Change, and then simplify.
Disadvantages: affects the whole body, poor scalability

Guess you like

Origin blog.csdn.net/Yosigo_/article/details/112124317