Python基础知识
# for循环
for i in range(50,100):
if i % 2 !=0 :
print(i, end='\t')
print("")
for i in range(100, 50, -1):
if i % 2 != 0:
print(i, end='\t')
result:
# break & continue
for floor in range(1, 7):
print(f"floor{floor}".center(50, '-'))
if floor == 3:
continue # 停止本次循环,进入下次循环
for room in range(1, 10):
if floor == 4 and room == 4:
print("dangerous...")
exit() # 退出程序
# break 结束整个循环(当前循环)
print(f"This room is {floor}0{room}".center(18, '*'))
result:
线性代数知识
# 使用前将numpy、numpy和scipy包安装入pycharm:设置-项目-Python解释器-+安装-搜索对应软件包
import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6]])
b = np.array([[1, 2], [3, 4], [5, 6]])
c = np.array([[1, 2, 3]])
d = np.array([[9, 8, 7], [3, 2, 1]])
print(f"a:{a}\nb:{b}\nc:{c}\nd:{d}")
# 矩阵加法
sum = a + d
print(f"a+d is:{sum}")
# 放缩
e = 3 * a
print(f"e :{e}")
# 数乘 矩阵乘
e = a * d
print(f"e :{e}")
# 转置
e = c.T
print(f"e :{e}")
e = np.array([[1, 2], [3, 4]])
print(f"e :{e}")
# 逆矩阵
result = np.linalg.inv(e)
print(f"e :{e}")
# 行列式
result = np.linalg.det(e)
print(f"e :{e}")
# 矩阵的秩
e = np.linalg.matrix_rank(d)
print(f"e :{e}")
运用python求一次方程的解
# sympy主要用于符号解,numpy和scipy主要用于数值解
数值解,有时为近似解,应用比较广泛
import numpy as np
A = np.array([[10, 1, -2], [-1, 10, -2], [-1, -1, 5]]) # 为系数矩阵
b = np.array([72, 83, 42]) # b为常数列
inv_A = np.linalg.inv(A) # A的逆矩阵
x = inv_A.dot(b) # A的逆矩阵与b做点积运算
# x = np.linalg.solve(A, b) # 可代替上两行
print(x)
result:#符号解
from sympy import symbols, Eq, solve
x, y, z = symbols('x y z')
eqs = [Eq(10 * x - y - 2*z, 72),
Eq(-x + 10 * y - 2*z, 83),
Eq(-x - y + 5*z, 42)]
print(solve(eqs, [x, y, z]))
result: