Study diary the second day of learning python

1. for statement -- traversal loop

for loop variable in traversal structure:

    Statement 1

else:

    Statement 2

2. while statement -- infinite loop

while condition:

    Statement 1

else:

    Statement 2

3. Circular reserved word

break: jump out of the innermost for or while loop. After jumping out of the loop, continue execution from the loop code

for s in "BIT":
    for i in range(10):
        print(s,end="")
        if s == "T":
            break


"""
BBBBBBBBBBIIIIIIIIIIT
"""

coutinue ends the current loop and jumps out of the following unexecuted statements in the loop body, but does not jump out of the current loop

for s in "PYTHON":
    if s == "T":
        continue
    print(s,end="")


"""
PYHON
"""
for s in "PYTHON":
    if s == "T":
        break
    print(s,end="")


"""
PY
"""

4. Random library (pseudo-random number)

seed(a=None)Initialize random number seed
random()Generate a random decimal of [0,1}
randint(a,b)Generate an integer between [a,b]
getrandits(K)Generates a random integer of K-bit length
randrange()Generates A random integer between A and B in X steps
uniform()Generate a random decimal between two numbers
choice()Returns a random element from a sequence type
shuffle()The elements in the sequence type are arranged randomly, and the scrambled sequence is returned
sample(pop,k)Select K elements randomly from the pop type

5. Monte Carlo methodvalue

from random import random
from math import sqrt
import time
DARTS = 10000
hits = 0.0
time.perf_counter()
for i in range(1,DARTS+1):
    x,y = random(),random()
    dist = sqrt(x**2 + y**2)
    if dist <= 1.0:
        hits = hits +1
pi = 4 * (hits/DARTS)
print("Pi Value is{}. ".format(pi))
print("The running time is:{:5.5}s".format(time.perf_counter()))

"""
Pi The value is 3.158. 
Run time is: 0.044677s
"""

6. Exception handling

try:

    Statement 1

Exception except ion type:

    Statement 2

try:
    num = eval(input("Please enter an integer:"))
    print(num **2)
except NameError:
    print("Input error, please enter an integer!")

try:

    Statement 1

except   Exception type 1:

    Statement 2

else:

    Statement 3

finally:

    Statement 4

7. Definition of function

Function is a reusable statement group with specific functions, which is represented by function name and called by function name.

Two purposes of using functions: reducing programming difficulty and code reuse

def   Function name     Parameters:

    Function body

    Return return value

def happy():
    print("Happy birthday to you!")
def happyB(name):
    happy()
    happy()
    print("Happy birthday,dear{}!".format(name))
    happy()
happyB("Mike")
print()
happyB("Lily")

"""
Happy birthday to you!
Happy birthday to you!
Happy birthday,dearMike!
Happy birthday to you!

Happy birthday to you!
Happy birthday to you!
Happy birthday,dearLicy!
Happy birthday to you!


"""

8. Function call

1) The caller pauses execution at the call

2) Copies the arguments to the formal parameters of the function at call time

3) Execute function body statement

4) When the function call ends, the return value is given, and the program returns to the pause before the call to continue execution

9. lambda function

lambda is a reserved word. This function defines an anonymous function, which means to return the function name as the result of the function

Function name = lambda   Parameter lists: expressions

f = lambda x,y : x + y
type(f)
print(f(10,22))


"""
32
"""

10. Parameter passing of function

def dup(str,times = 2):
    print(str * times)
dup("knock!")
dup("knock!",4)

"""
knock!knock!
knock!knock!knock!knock!
"""

There are default values for parameters. You can directly specify default values for these parameters when defining a function;

When calling a function, you need to input parameters in order, and optional parameters must be defined after non optional parameters;

Variable quantity parameters can be designed by adding an asterisk before the parameters. Variable parameters with an asterisk can only appear at the end of the parameter list

def vfunc(a, *b):
    print(type(b))
    for n in b:
        a += n
    return a
print(vfunc(1,2,3,4,5))   #1 is assigned to a, 2, 3, 4 and 5 are b, and b is a tuple

"""
<class 'tuple'>
15
"""

11. Return value of function

return statementreturns a function and returns the program to the location where the function was called to continue execution

The function can also have no return statement and does not return a value at this time

The function can have multiple returns and return multiple values

12. Variable of function

There are two kinds of variables in the program: global variables and local variables

Global variable: a variable defined outside a function

Global variable: a variable used within a function. It is only valid within a function

n  = 1
def func(a,b):
    c = a * b
    return c
s = func("knock!",2)
print(c)


"""
Traceback (most recent call last):
  File "F:\Tools\pythonProject\main.py", line 6, in <module>
    print(c)
NameError: name 'c' is not defined
"""
n = 1
def func(a,b):
    n = b
    return a * b
s = func("knock!",2)
print(s,n)

"""
knock!knock! 1
"""

global n can make n a global variable

ls = []
def func(a,b):
    ls.append(b)
    return a*b
s = func("konck!",2)
print(s,ls)


# konck!konck! [2]

Note that the list changes after the func function is called. This is because the combined data types such as list can be created and referenced separately in use because they operate on multiple data.

When the list variable is assigned by [], the list is actually created. Otherwise, it is a reference before.

If there is a list with the name ls that has been actually created inside the func function, the func function will operate on the list and will not modify the global variables

13. datetime Library

It provides a series of time processing methods from simple to complex

datetime.dateDate representation class
datetime.timeTime representation class
datetime.datetimeDate and time representation class
datetime.timedeltaClasses related to time intervals
datetime.tzinfoTime zone related information representation class

1) datetime.now() gets the current time and event object

2) datetime.utcnow() gets the UTC world standard time corresponding to the current date and time

3) datetime(year,month,day,hour,minute,second,microsecond) constructs a date and time object

4) . min returns the minimum time object

5) . max returns the maximum time object

6) . year returns the year contained

7) . month returns the included month

8) . day returns the included date

9) . hour returns the hours contained

10) . minute returns the contained minutes

11) . second returns the seconds contained

12) . microsecond returns the contained clock

13) . isoformat uses ISO 8601 standard to display time

14) . isoweekday returns 1-7 after calculating the week based on the date

15) . strftime is a method of format display according to the format string format

18. strftime() method

The most effective way to format time

%Y represents the year,% m represents the month,% B represents the month name and% B represents the abbreviation of the month name

%d represents date,% a represents week,% a represents week abbreviation, and H represents hour

%I represents hour (12 hour system)% p represents morning or afternoon% M represents minute% S represents second

The strftime method formats the left side of the number in the string and automatically fills in zero

19. Seven segment nixie tube drawing

Input: the numeric form of the current date

Processing: draw seven segments of nixie tube representation according to each number

Output: draws the current seven segment digital representation

import turtle,datetime
def drawLine(draw):
    turtle.pendown() if draw else turtle.penup()
    turtle.fd(40)
    turtle.right(90)
def drawDight(d):
    drawLine(True) if d in [2,3,4,5,6,8,9] else drawLine(False)
    drawLine(True) if d in [0,1,3,4,5,6,7,8,9,] else drawLine(False)
    drawLine(True) if d in [0,2,3,5,6,8,9] else drawLine(False)
    drawLine(True) if d in [0,2,6,8] else drawLine(False)
    turtle.left(90)
    drawLine(True) if d in [0,4,5,6,8,9] else drawLine(False)
    drawLine(True) if d in [0,2,3,5,6,7,8,9] else drawLine(False)
    drawLine(True) if d in [0,1,2,3,4,7,8,9] else drawLine(False)
    turtle.left(180)
    turtle.penup()
    turtle.fd(20)
def drawDate(date):
    for i in date:
        drawDight(eval(i))
def main():
    turtle.setup(800,350,200,200)
    turtle.penup()
    turtle.fd(-300)
    turtle.pensize(5)
    drawDate(datetime.datetime.now().strftime('%Y%m%d'))
    turtle.hideturtle()
main()

20. Code reuse and modular design

The direct benefit of function encapsulation is code reuse

Process oriented programming is a programming method with process description as the main method

Object is a high-level abstract way of program. It organizes program code into higher-level classes. Objects include attributes representing object characteristics and methods representing object operations, that is, they are composed of attributes and methods.

Modular design is to reasonably divide the functional modules of the program and design the program based on the module. Usually, the program is divided into main program, subroutine and the relationship between subroutines

Tight coupling: function blocks shall be reasonably divided as far as possible, and the internal coupling of function blocks shall be close

Loose coupling: the relationship between modules shall be as simple as possible, and the coupling degree between functional blocks shall be low

21. Function recursion

The function is called by the internal code of the function, that is, the function itself

There are one or more base cases, which do not need to be recursive again, and it determines the expression

All recursive chains must end with one or more base instances

# Factorial
def fact(n):
    if n == 0:
        return 1
    else:
        return n * fact(n-1)
num = eval(input("Please enter an integer:"))
print(fact(abs(int(num))))
#String inversion

def reverse(s):
    return reverse(s[1:]) + s[0]
reverse("ABC")

"""
RecursionError: maximum recursion depth exceeded Beyond base case
"""
def reverse(s):
    if s == "":
        return s
    else:
        return reverse(s[1:]) + s[0]
str = input("Please enter a string:")
print(reverse(str))

22. Draw koch curve

The positive integer n represents the order of the koch curve and the number of operations in the process of generating the koch curve. The initialization order of the koch curve is 0, which represents a straight line with a length of L. L is divided into three segments, and the middle segment is replaced by two edges of an equilateral triangle with a side length of L/3 to obtain the koch curve of order 1, including four segments. Repeat to obtain the koch curve of order n immediately.

import turtle
def koch(size,n):
    if n== 0:
        turtle.fd(size)
    else:
        for angle in [0,60,-120,60]:
            turtle.left(angle)
            koch(size/3,n-1)
def main():
    turtle.setup(800,400)
    turtle.speed(0)
    turtle.penup()
    turtle.goto(-300,-50)
    turtle.pendown()
    turtle.pensize(2)
    koch(600,3)
    turtle.hideturtle()
main()

  23. python built-in functions

python provides 68 built-in functions

allidroundcompilelocalsabs
inputsetdirmapanyint
sortedexecmenmoryviewascilenstr
enumeratenextbinlisttuplefilter
objectboolmaxtypeformatproperty
chrminzipfrozensetreprcomplex
octgetattrsetattrdictpoengolbals
silcedivmodordbyteshasattreval
powstaticmethoddelattrhelpsumfloat
printbytearraysuperisinstanceissubclasshash
rangecallableissubclassvarshexreversed
classmethoditer_import_

24. Combined data type

It can be divided into three categories:

Sequence type: an element vector. There is a sequence relationship between elements. Accessed through sequence number, elements are not exclusive

Collection type: a collection of elements. Elements are out of order. The same elements exist only in the collection

Mapping type: a combination of key value data items. Each element is a key value pair

25. Sequence type

One dimensional element vector. There is a sequential relationship between elements, which can be accessed through sequence number

There are three types: string, tuple and list

String: an ordered combination of single characters

Tuple: an immutable sequence containing 0 or more data items

List: you can modify the sequence of data items

26. Sequence type operators and functions

x in sReturns True if x is an element of s; otherwise, returns False
x not in sReturns True if x is not an element of s; otherwise, returns False
s+tConnect s and t
s*n

Copy s n times

s[i]Index returns the i th element
s[i:j]Fragment, return the s-th to j-1 st elements
s[i:j:k]Slice and return the i to j-1 subsequence with k as step
len(s)Number of elements of s
min(s)Smallest element in s
max(s)Maximum element in s
s.index(x,i,j)Where x first appears from J to j
s.count(x)

Total number of occurrences of x

27. Tuple

Once created, it cannot be modified. It is represented by parentheses

28. Collection type

Contains an unordered combination of 0 or more data items. The element cannot be repeated. The element type can only be a fixed data type

Any type that can be hashed can be used as a collection element

Data type set

Aggregation does not have the concept of index and location, and cannot be segmented. It is represented by {}

29. Set type operator

S-T or S.differenceReturns a new collection of elements in S that are not in T

S-=T or S.difference_update()

Update set, element in S not in T
S & T or S.intersection_update()Returns a new collection of elements in both S and T
S & = t or S.intersection_update()Update the set with elements in both S and T
S^T or S.symmetric_difference()New set, elements of sets S and T, and do not include elements in both at the same time
S=^TUpdate set, ditto
S|TA new set containing all elements of S and T
S=|TUpdate set S includes all elements in sets S and T
S<=TS is the same as t or s is a subset of T. return True otherwise False
S>=T

S is the same as T or s is a T superset, return True, otherwise Fasle

30. Mapping type

Key pair value type, each element is a key value pair, and the elements are out of order.

Mainly dictionary type.

31. List type

List list is an ordered sequence containing 0 or more object references, which belongs to sequence type.

The list is very flexible and supports a variety of operators and functions

32. List type operation

ls[i]=xReplace the ith element with x
ls[i:j]=ltReplace elements from i to j-1 in ls with list lt
ls[i:j:k]=ltlt replaces the elements in the list ls in steps k from i to j-1
delĀ delete
del[i:j:k]

Delete k-step elements from i to j-1

ls+=lt or ls.extend()Add lt to ls
ls*=nCopy n times ls
ls.appendFinally, add the element
ls.clearDelete all elements
ls.copyGenerate a new list and copy all elements
ls.insert(i,x)Insert x in position i
ls.remove(x)The first element x is deleted
ls.reverse(x)Element inversion
ls.pop(i)

Take out the ith element and delete it

33. Calculation of basic statistical value

Input: obtain a set of data from user input, file, network, etc

Processing: appropriate data structures and algorithms

Output: mean, standard deviation and median

from math import sqrt
def getNum():
    nums = []
    iNumStr = input("Please enter a number (press enter directly to exit):")
    while iNumStr != "":
        nums.append(eval(iNumStr))
        return nums
def mean(numbers):
    s = 0.0
    for num in numbers:
        s = s + num
    return s / len(numbers)
def dev(numbers,mean):
    sdev = 0.0
    for num in numbers:
        sdev = sdev + (num - mean)**2
    return sqrt(sdev / (len(numbers)-1))
def median(numbers):
    sorted(numbers)
    size = len(numbers)
    if size % 2 == 0:
        med = (numbers[size//2]-1 + numbers[size//2])/2
    else:
        med = numbers[size//2]
    return med
n = getNum()
m = mean(n)
print("Average:{},Variance:{},median:{}.".format(m,dev(n,m),median(n)))

When this code runs in pycharm, the error of zero division error: float division by zero will appear, and the cause is still being investigated

34. Dictionary type

For key pair values, see the previous introduction and will not be described in detail.

35. Dictionary type operation

.keys()Return all keys
.values()Return all values
.items()Returns all key value pairs
.get()If the key exists, the corresponding value will be returned; otherwise, the default value will be returned
.pop()If the key is pressed, the corresponding value will be returned, and the key value pair will be deleted. Otherwise, the default value will be returned
.popitem()Randomly take a key value pair from the dictionary and return it as a tuple
.clear()Delete all key value pairs
delĀ Delete a key value pair in the dictionary
key in dKey returns True in the dictionary, otherwise False

36. jieba Library

A third-party Chinese word segmentation function library

Installation method: pip install jieba

jieba library supports three word segmentation modes:

Precise mode: the most accurate separation of sentences, which is most suitable for text analysis

Full mode: scan all the words that can be formed into words in the sentence, but it can't eliminate ambiguity

Search engine mode: segment long words again on the basis of accurate mode

37. Common word segmentation functions of jieba Library

jieba.cut()Precise mode, which returns an iteratable data type
jieba.cut(s,cut_all=True)Full mode, output all possible words in text s
jieba.cut_for_search(s)Search engine mode, suitable for word segmentation results indexed by search engines
jieba.lcut(s)Precise mode, return 1 List Model
jieba.lcut(s,cut_all=True)Full mode, return a list model
jieba_lcut_for_search(s)

Search engine mode, return a list model

jieba.add_word(w)

Add a new word to the word segmentation dictionary w

38. Text word frequency statistics

Statistics of the maximum 10 word frequencies of English hamlet

def getText():
    txt = open("hamlet.txt","r").read()
    txt = txt.lower()
    for ch in '!"$%&()*+-,./:;<=>?@[\\]^_`{|}~':
        txt = txt.replace(ch,"")
    return txt
hamletTxt = getText()
words = hamletTxt.split()
counts = {}
for word in words:
    counts[word] = counts.get(word,0) +1
items = list(counts.items())
items.sort(key = lambda x:x[1],reverse=True)
for i in range(10):
    word,count = items[i]
    print("{0:<10}{1:>5}".format(word,count))

"""
the        1137
and         963
to          736
of          669
you         546
i           540
a           527
my          513
hamlet      459
in          435

"""

Note that the text should be placed in the python project folder to read txt. The text has been placed in my space and can be accessed by myself.

39. Statistics on the number of appearances in the mission of the romance of the Three Kingdoms

If present  ' utf-8 'codec can't decode byte 0xa1 in position 0: invalid start byte is probably a coding problem. When saving text txt, you should choose utf-8 format, as shown in the figure.

As above, txt text needs to be fetched in the space.  

import jieba
txt = open("Romance of the Three Kingdoms.txt","r",encoding='utf-8').read()
words = jieba.lcut(txt)
counts = {}
for word in words:
    if len(word) == 1:
        continue
    else:
        counts[word] = counts.get(word,0) +1
items = list(counts.items())
items.sort(key = lambda x:x[1],reverse=True)
for i in range(15):
    word,count = items[i]
    print("{0:<10}{1:>5}".format(word,count))

"""
Building prefix dict from the default dictionary ...
Dumping model to file cache C:\Users\14375\AppData\Local\Temp\jieba.cache
Loading model cost 0.561 seconds.
Prefix dict has been built successfully.
Cao Cao          nine hundred and fifty-three
 kong ming          eight hundred and thirty-six
 general          seven hundred and seventy-two
 But say          six hundred and fifty-six
 Xuande          five hundred and eighty-five
 Guan Yu          five hundred and ten
 the prime minister          four hundred and ninety-one
 Two people          four hundred and sixty-nine
 must not          four hundred and forty
 Jingzhou          four hundred and twenty-five
 Xuande said         three hundred and ninety
 Kong Mingyue         three hundred and ninety
 No          three hundred and eighty-four
 such          three hundred and seventy-eight
 Fei Zhang          three hundred and fifty-eight

"""

Upgrade

import jieba
excludes = {"general","But say","Jingzhou","Two people","must not","No","such"}
txt = open("Romance of the Three Kingdoms.txt","r",encoding='utf-8').read()
words = jieba.lcut(txt)
counts = {}
for word in words:
    if len(word) == 1:
        continue
    elif word == 'Zhuge Liang' or word == 'Kong Mingyue' or word == "Prime Minister Zhuge":
        rword = "kong ming"
    elif word == "Guan Yu" or word == "Cloud length":
        rword = "Guan Yu"
    elif word == "Xuande" or word == "Xuande said":
        rword ="Liu Bei"
    elif word == "Monde" or word == "Prime Minister Cao Cheng":
        rword = "Cao Cao"
    else:
        rword = word
    counts[rword] = counts.get(rword,0) +1
for word in excludes:
    del(counts[word])
items = list(counts.items())
items.sort(key = lambda x:x[1],reverse=True)
for i in range(5):
    word,count = items[i]
    print("{0:<10}{1:>5}".format(word,count))

The code written by the original author has a big logical loophole. Originally, he directly assigned the prime minister to Cao Cao. In fact, Zhuge Liang is also the prime minister. Therefore, it is difficult to judge whether the prime minister refers to Cao Cao or Zhuge Liang. And this code is not rigorous, so it can only be used as an entertainment program. Don't take it seriously.

Tags: Python

Posted on Wed, 01 Dec 2021 23:48:04 -0500 by kidintraffic