Introduction to Python to mastery

Keywords: Python data structure

Function (I)

  • Function parameters do not need to declare types, nor do they need to specify the return value type of the function
  • Function does not accept arguments, but also keep a pair ()
  • After the brackets:

Basic syntax of function definition and call

Example 1: Fibonacci sequence

def fib(n):
    a, b = 1, 1
    while a < n:
          print(a, end=' ')
          a, b = b, a+b

Example 2: prime factor decomposition by recursive method

from random import randint

def factors(num):
    #Find the factor from 2 each time
    for i in range(2, int(num**0.5)+1):
    #Find a factor
    if num%i == 0:
       #Continue to decompose the quotient and repeat the process
       #Note that break is very important
       #Indecomposability is itself a factor
facs = []
n  = randint(2, 10**8)
results = '*'.join(map(str, facs))
if n==eval(result):
    print(n, '= '+result)

Sequence unpacking when passing parameters

def demo(a, b, c):

seq = [1, 2, 3]

tup = (1, 2, 3)
def demo(a, b, c):
print(a, b, c)

dic = {'a':1,'b':2,'c':3}

Variable scope

>>> def demo():
global x
x = 3
y = 4

>>> x = 5
>>> demo()
3 4
>>> x
>>> y
NameError: name 'y' is not defined

1. In this code, there is a global variable x outside the function, so the keyword global in the function is used to declare to use and modify the existing global variable x outside.

2. The variable y in the function has no declaration. It is a local variable by default. It no longer exists after the function is run. Therefore, the code throws an exception when accessing outside the function.

lambda expressions

>>>f = lambda x, y, z:x+y+z
>>>g = lambda x, y=2, z=3: x+y+z
>>>g(2, z=4, y=5)
>>> L = [1,2,3,4,5]
>>>print(list(map(lambda x: x+10, L)))
>>>data.sort(key=lambda x: len(str(x)))
>>>data.sort(key=lambda x: len(str(x)), reverse=True)#Descending order

Key points of generator function design

  • Include yield statement
  • Similar to the return statement, it is used to return a value. Difference: after returning the value, the operation of the following code will be suspended or suspended, and the next time it passes through the generator object__ next()__ () method, built-in function next () method for loop through the generator object element or display the "request" data in other ways.
  • The generator has the characteristics of inert value and is suitable for big data processing.

  Generator function that can generate Fibonacci sequence

>>>def f():
   a, b = 1, 1
   while True:
          yield a
          a, b = b, a+b

>>>a = f()
>>>for i in range(10):
   print(a.__next__(), end=' ')

1. The generator expression returned when calling the generator function is not a specific value.

2. You can use the of the generator object__ next__ The () method returns each value in the generator object one by one from front to back. The generator object uses yield to return a value, then pauses the execution of the code and uses it again__ next__ () resume execution when the method asks for a value.

Wonderful cases

Write a function that accepts string parameters and returns a tuple, where the first element is the number of uppercase letters and the second element is the number of lowercase letters:

def demo(s):
    result = [0, 0]
    for ch in s:
        if ch.islower():
           result[1] += 1
        elif ch.isupper():
           result[0] += 1
     return tuple(result)

Print Yang Hui triangle:

def yanghui(t):
    line = [1, 1]
    for j in rang(2,t)
        r = []
        for j in range(0, len(line)-1):
        line = [1]+r+[1]

Write a function, accept a positive even number as a parameter, output two prime numbers, and the sum of the two prime numbers is equal to the original positive even number. If there are multiple groups of prime numbers that meet the conditions, all are output.

def demo(n):
    def IsPrime(p):
        if p == 2:
            return True
        if p%2 == 0:
           return False
        for i in range(3,int(p**0.5)+1, 2):
           if p%i==0:
            return False
       return True

      if isinstance(n, int) and n>0 and n%2==0:
          for i in range(2, n//2+1):
               if IsPrime(i) and Isprime(n-i):
                  print(i,'+', n-i,'=', n)

Write a function to calculate the accuracy of string matching.

def Rate(origin, userInput):
    if not (isinstance(origin, str) and isinstance(userInput, str)):
    right = sum(1 for o, u in zip(origin, userInput) if o==u)
    return round(right/len(origin), 2)

Simulated counting game: n people form a circle and number them in sequence. Start from the first person and count from one to k. The person reporting k goes out of the circle, and then the circle shrinks. Continue the game from the next person and ask what the original number is left.

from itertools import cycle
def demo(lst, k):
    #Slice and affect the original data
    t_lst = lst[:]
    #The game went on until there was only one person left
    while len(t_lst): 
         #Create a cycle object
         c = cycle(t_lst)
         #Report from 1-k
         for i in range(k):
              t = next(c)
         #One out, the circle narrowed
         index = t_lst.index(t)
         t_lst = t_lst[index+1:] + t_lst[:index]
     #game over
     return t_lst[0]

lst = list(range(1,11))
print(demo(lst, 3))

while Loop

while True:
      r = input('Do you want to try once more?(y/n)')
      if r == 'n':

Posted by unibroue on Thu, 18 Nov 2021 20:10:19 -0800