1. A brief tutorial on Python
- Long statements can be broken into multiple lines with the continuation symbol “\”. If a statement contains a pair of parentheses (), we can split the statement anywhere between them without using the continuation symbol “\”
a, b, c, d = 4.5.5.1.5+2j.'a'
e = 6.0 * a - b * b + \ # follow up with "\"
c ** (a + b + c)
f = 6.0 * a - b * b + c ** ( # newline with ()
a + b + c)
Copy the code
- Plural definition: A Python complex number can be explicitly defined as such
C = 1.5-0.4 j
Python withjRepresents an imaginary unit - Construct single-element tuples: expressions
(foo)
The correct tuple construction syntax is(foo, )
- List parsing: List parsing is compact and faster, especially for long lists, because you don’t have to explicitly construct the for loop structure
L1 = [2.3.5.7.11.14]
L2 = [] # Empty list
L2 = [x**2 for x in L1] Construct L2 from the square of elements in the L1 list
L2 = [x*x for x in L1 if x%2] Construct L2 from the square of the odd elements in the L1 list
L2 = [x*y for x in L1 if x%2 for y in L1 if not y%2] Construct L2 from the product of odd and even numbers in L1 list
Copy the code
- Specification of the initial function definition (content delay condition) :
# TBD: finish this function
def function() :
Describe the specific function of the function. Use docstrings to describe functions
pass
Copy the code
- The different argument types of the function
def foo1(a, b, c) : pass # position parameter
def foo2(a, b=7, c='i') : pass # Keyword argument
def foo3(*args) : pass # Variable number of positional arguments
def foo4(a, b, *args, **kwargs) : pass # variable number of keyword arguments
Copy the code
- Formatted output:
a, b, c, d = 5.123.45678.1234567.89.'abc'
print("% 5 d % 010.3 f, % 13.4 e, % - 6 s |" % (a, b, c, d) )
# %5d: Output five characters, justify values to the right, and fill the blanks with Spaces
# %010.3f: Prints a string of 10 character widths, aligned to the right, padded with zeros
# %13.4e: A field with a 13-character output value reserved after four decimal places, using scientific notation (e)
# %-6s: Prints fields of 6 character widths, left-aligned characters, filled with Spaces
Copy the code
- Circulation technique
The enumera() function provides two arguments during each loop, the first representing the index value of the list element and the second representing the contents of the list element
fruit = ["apple"."pear"."pineapple"."orange"."banana"]
for i, x in enumerate(fruit):
print(i, x)
Copy the code
- Dictionary merge operations
a = {"ross": "123456"."xiaoming": "abc123"}
b = {"lilei": "111111"."zhangsan": "12345678"}
c = {**a, **b} Unpack the contents of the dictionary A and B directly into here
print(c)
Copy the code
- Ternary operator
score = 99
s = "pass" if score > 60 else "fail" If the condition after the ternary operator is met, the expression prints the preceding value, otherwise it prints the else value
Copy the code
2. NumPy
Create an array
import numpy as np
m1 = np.array([1.2.3.4.5]) Create an array from array
m2 = np.zeros((3.2)) # create 3 rows and 2 columns with zeros
m3 = np.ones((2.2)) Create a 1 matrix with 2 rows and 2 columns
m4 = np.arange(3.7) Create incrementing or decrementing arrays with arange
m5 = np.linspace(0.1.5) # linspace creates numbers that are evenly spaced between two numbers
m6 = np.random.rand(2.4) Use random. Rand to create a random number array
Copy the code
- In NumPy, the default data type of an array is a 64-bit floating-point number, but we can create an array using the
dtype
Specify additional data types
m = np.zeros((3.2), dtype=np.int32)
# 整型 np.int8/16/32/64
uint8/16/32/64
# Np.float32/64
# Boolean value bool
# string STR
Copy the code
- For existing arrays, we can also pass
astype(...)
To convert the data type
Basic operation
import numpy as np
a1 = np.array([1.2.3])
a2 = np.array([4.5.6])
b1 = np.arange(9).reshape(3.3)
b2 = np.ones((3.3))
print(f"a1+b1: {a1+b1}") # Extend the two arrays to the same dimension
print(F "a1, a2:{np.dot(a1, a2)}") # dot product
print(f"b1@b2: {b1@b2}") # Matrix multiplication
print(f"sqrt(a1): {np.sqrt(a1)}") # Take the square root of all numbers
print(f"sin(a1): {np.sin(a1)} cos(a1): {np.cos(a1)}") # Triangulate all numbers in turn
print(f"log(a1): {np.log(a1)} power(a1): {np.exp(a1)}") # Perform logarithmic, exponential operations on all numbers
print(f"min(a1): {np.min(a1)} max(a1): {np.max(a1)}") Return the smallest and largest element of the array
print(f"argmin(a1): {np.argmin(a1)} argmax(a1): {np.argmax(a1)}") # return the index of the smallest and largest element in the array
print(f"sum(a1): {np.sum(a1)} mean(a1): {np.mean(a1)} median(a1): {np.median(a1)}") Return the sum, average, and median of the array elements
print(f"var(a1): {np.var(a1)} std(a1): {np.std(a1)}") Return the variance and standard deviation of the elements in the array
print(f"a1*5: {a1*5}") Multiply all the numbers in A1 by 5 to produce a new array of the same size
# a1. Func ()
# In multidimensional arrays, the above function can specify an additional parameter axis in parentheses: axis=0 corresponds to the row and axis=1 corresponds to the column
print(b1[0.1]) Select * from row 1, column 2
print(b1[0.0:2]) Select * from row 1, columns 1 and 2
print(b1[::-1]) # -1 is the span, which means the array is reversed
print(b1[(b1 > 3) & (b1 % 2= =0)]) Select the number that matches the criteria in b1
Copy the code
SymPy: A Computer algebra system
- SymPy is a Python scientific computing library that provides a strong system of symmetries to complete such computational problems as polynomial evaluation, limit evaluation, equation solution, integral evaluation, differential equations, series expansion, matrix operation and so on.
- The most significant feature of the SymPy is that it is entirely written in Python and is really just an additional module to Python. It is small enough to work on any Python system. It works well with the NumPy interface for numerical processing and with the Matplotlib interface for graphical output.
import sympy as sy
# sympy built-in notation
print(sy.I, sy.I**2, sy.sqrt(-1)) # imaginary number I, I ^2, square root of minus 1
print(sy.E, sy.log(sy.E)) # Natural logarithm e, lne
print(sy.oo, 1/sy.oo, 1+sy.oo) # up, 1 / up, 1 + up
print(sy.pi, sy.sin(sy.pi/2)) # PI, sin (PI / 2)
# Elementary operations
print(sy.log(sy.E)) # find the logarithm (ln)
print(sy.sqrt(-1)) # take the square root
print(sy.root(8.3)) # Find the NTH root (the 3rd root of 8)
print(sy.sin(sy.pi)) # find the trig function
print(sy.factorial(4)) # please factorial
Copy the code
- SymPy can also be expressed and evaluated, formula (group), sum (sigma), limit, derivative, and (non) definite integral, etc. See the third reference
4. Reference materials
- Scientific Computation in Python (Original Book, 2nd Edition)
- Bilibili – Quiro Programming Paradise
- SymPy Library