10 2024 档案
摘要:#程序文件ex7_4.py import numpy as np from scipy.interpolate import interp1d from scipy.interpolate import lagrange import pylab as plt a = np.loadtxt('dat
阅读全文
摘要:#程序文件ex7_3.py import numpy as np import pylab as plt from scipy.interpolate import lagrange yx = lambda x: 1/(1+x**2) def fun(n): x = np.linspace(-5,
阅读全文
摘要:import numpy as np matches = np.array([ [0, 1, 0, 1, 1, 1], # 1队 [0, 0, 0, 1, 1, 1], # 2队 [1, 1, 0, 1, 0, 0], # 3队 [0, 0, 0, 0, 1, 1], # 4队 [0, 0, 1,
阅读全文
摘要:import numpy as np distances = np.array([ [0, 2, 7, np.inf, np.inf, np.inf], [2, 0, 4, 6, 8, np.inf], [7, 4, 0, 1, 3, np.inf], [np.inf, 6, 1, 0, 1, 6]
阅读全文
摘要:import pylab as plt import numpy as np ax=plt.axes(projection='3d') X = np.arange(-6, 6, 0.25) Y = np.arange(-6, 6, 0.25) X, Y = np.meshgrid(X, Y) Z =
阅读全文
摘要:import pylab as plt import numpy as np x=np.linspace(-4,4,100); x,y=np.meshgrid(x,x) z=50*np.sin(x+y); ax=plt.axes(projection='3d') ax.plot_surface(x,
阅读全文
摘要:import pylab as plt import numpy as np ax=plt.axes(projection='3d') #设置三维图形模式 z=np.linspace(-50, 50, 1000) x=z**2*np.sin(z); y=z**2*np.cos(z) plt.plot
阅读全文
摘要:import pylab as plt import numpy as np plt.rc('text', usetex=True) #调用tex字库 y1=np.random.randint(2, 5, 6); y1=y1/sum(y1); plt.subplot(2, 2, 1); str=['
阅读全文
摘要:import pandas as pd import pylab as plt plt.rc('font',family='SimHei') #用来正常显示中文标签 plt.rc('font',size=16) #设置显示字体大小 a=pd.read_excel("data2_52.xlsx",he
阅读全文
摘要:import pandas as pd import pylab as plt plt.rc('font',family='SimHei') #用来正常显示中文标签 plt.rc('font',size=16) #设置显示字体大小 a=pd.read_excel("data2_52.xlsx", h
阅读全文
摘要:import numpy as np import sympy as sp a = np.identity(4) #单位矩阵的另一种写法 b = np.rot90(a) c = sp.Matrix(b) print('特征值为:', c.eigenvals()) print('特征向量为:\n',
阅读全文
摘要:import sympy as sp x = sp.var('x:2') #定义符号数组 s = sp.solve([x[0]**2+x[1]**2-1,x[0]-x[1]], x) print(s) print("学号:3008") 结果如下
阅读全文
摘要:import sympy as sp sp.var('x1,x2') s=sp.solve([x1**2+x2**2-1,x1-x2],[x1,x2]) print(s) print("学号:3008") 结果如下
阅读全文
摘要:import sympy as sp a, b, c, x=sp.symbols('a,b,c,x') x0=sp.solve(a*x**2+b*x+c, x) print(x0) print("学号:3008") 结果如下:
阅读全文
摘要:from scipy.sparse.linalg import eigs import numpy as np a = np.array([[1, 2, 3], [2, 1, 3], [3, 3, 6]], dtype=float) #必须加float,否则出错 b, c = np.linalg.e
阅读全文
摘要:from scipy.optimize import least_squares import numpy as np a=np.loadtxt('data2_47.txt') x0=a[0]; y0=a[1]; d=a[2] fx=lambda x: np.sqrt((x0-x[0])**2+(y
阅读全文
摘要:from scipy.integrate import quad def fun42(x, a, b): return a*x**2+b*x I1 = quad(fun42, 0, 1, args=(2, 1)) I2 = quad(fun42, 0, 1, args=(2, 10)) print(
阅读全文
摘要:import numpy as np from scipy.sparse.linalg import eigs import pylab as plt w = np.array([[0, 1, 0, 1, 1, 1], [0, 0, 0, 1, 1, 1], [1, 1, 0, 1, 0, 0],
阅读全文
摘要:def X(n): # 差分方程的解 return 2 * (-1)**(n + 1) n_values = [0, 1, 2, 3, 4, 5] for n in n_values: print(f"X({n}) = {X(n)}") print("学号:3008") 结果如下
阅读全文
摘要:import numpy as np def f(x): return (abs(x + 1) - abs(x - 1)) / 2 + np.sin(x) def g(x): return (abs(x + 3) - abs(x - 3)) / 2 + np.cos(x) # 假设我们有一些初始猜测
阅读全文
摘要:import numpy as np from scipy.linalg import eig # 定义矩阵 A = np.array([[-1, 1, 0], [-4, 3, 0], [1, 0, 2]]) # 计算特征值和特征向量 eigenvalues, eigenvectors = eig(
阅读全文
摘要:import numpy as np def f(x): return (abs(x + 1) - abs(x - 1)) / 2 + np.sin(x) def g(x): return (abs(x + 3) - abs(x - 3)) / 2 + np.cos(x) from scipy.op
阅读全文
摘要:from scipy.integrate import quad import numpy as np # 第一部分:抛物线旋转体(修正后) def V1_quad(y): return np.pi * (4*y - y**2) V1_corrected, _ = quad(V1_quad, 1,
阅读全文
摘要:import sympy as sp # 定义变量 x, y = sp.symbols('x y') # 定义方程组 equation1 = sp.Eq(x**2 - y - x, 3) equation2 = sp.Eq(x + 3*y, 2) # 解方程组 solutions = sp.solv
阅读全文
摘要:import numpy as np # 初始化系数矩阵A和常数项向量b n = 1000 A = np.zeros((n, n)) b = np.arange(1, n+1) # 填充系数矩阵A for i in range(n): A[i, i] = 4 # 对角线元素为4 if i < n-1
阅读全文
摘要:import numpy as np # 定义系数矩阵A和常数项向量b A = np.array([[2, 3, 1], [1, -2, 4], [3, 8, -2], [4, -1, 9]]) b = np.array([4, -5, 13, -6]) # 使用numpy的lstsq函数求解最小二
阅读全文
摘要:import numpy as np # 定义系数矩阵A和常数项向量b A = np.array([[4, 2, -1], [3, -1, 2], [11, 3, 0]]) b = np.array([2, 10, 8]) # 使用numpy的lstsq求解最小二乘解 x, residuals, r
阅读全文
摘要:import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # 模拟高程数据(假设数据已经过某种方式插值或生成) # 这里我们创建一个简单的40x50网格,并填充随机高程值 x
阅读全文
摘要:#椭圆抛物面 import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # 定义参数u和v u = np.linspace(-2, 2, 400) v = np.linspac
阅读全文
摘要:import numpy as np #单叶双曲面 import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # 定义参数u和v u = np.linspace(-2, 2, 400) v = np.linspac
阅读全文
摘要:import numpy as np import matplotlib.pyplot as plt # 定义x的范围 x = np.linspace(-10, 10, 400) # 创建一个2行3列的子图布局 fig, axs = plt.subplots(2, 3, figsize=(12, 8
阅读全文
摘要:import numpy as np import matplotlib.pyplot as plt # 定义x的范围 x = np.linspace(-10, 10, 400) # 创建一个图形和坐标轴 plt.figure(figsize=(10, 6)) ax = plt.gca() # 循环
阅读全文
摘要:import numpy as np import matplotlib.pyplot as plt from scipy.integrate import quad def fun(t, x): return np.exp(-t) * (t ** (x - 1)) x = np.linspace(
阅读全文
摘要:import numpy as np import matplotlib.pyplot as plt # 定义 x 的范围 x = np.linspace(-5, 5, 400) # 计算三个函数的值 y_cosh = np.cosh(x) y_sinh = np.sinh(x) y_half_ex
阅读全文
摘要:from scipy.optimize import fsolve,root fx = lambda x:[x[0]**2+x[1]**2-1,x[0]-x[1]] s1=fsolve(fx,[1,1]) s2=root(fx,[1,1]) print(s1,'\n',' ');print(s2)
阅读全文
摘要:from scipy.optimize import fsolve,root fx=lambda x: x**980-5.01*x**979+7.39*x**978-3.388*x*977-x**3+5.01*x**2-7.398*x+3.388 #函数被调用4000次 x1=fsolve(fx,1
阅读全文
摘要:import numpy as np a = np.random.rand(6,8) np.savetxt("data2_43_1.txt",a) np.savetxt("data2_43_2.csv",a,delimiter=',') b=np.loadtxt("data2_43_1.txt")
阅读全文
摘要:with open('data2_2.txt') as fp: L1=[];L2=[] for line in fp: L1.append(len(line)) L2.append(len(line.strip())) data = [str(num) + '\t'for num in L2] pr
阅读全文
摘要:import pandas as pd import numpy as np a = pd.DataFrame(np.random.randint(1,6,(5,3)), index=['a','b','c','d','e'], columns=['one','two','three']) a.lo
阅读全文
摘要:import pandas as pd import numpy as np d = pd.DataFrame(np.random.randint(1,6,(10,4)),columns = list("ABCD")) d1 = d[:4] d2 = d[4:] dd= pd.concat([d1,
阅读全文
摘要:import pandas as pd a = pd.read_csv("data2_38_2.csv",usecols=range(1,5)) b = pd.read_excel("data2_38_3.xlsx","Sheet2",usecols=range(1,5)) print("学号:30
阅读全文
摘要:import pandas as pd import numpy as np datas = pd.date_range(start='20191101',end='20191124',freq='D') a1 = pd.DataFrame(np.random.randn(24,4),index =
阅读全文
摘要:import pandas as pd import numpy as np datas = pd.date_range(start='20191101',end='20191124',freq = 'D') a1 = pd.DataFrame(np.random.randn(24,4),index
阅读全文
摘要:import numpy as np a = np.eye(4) b = np.rot90(a) c,d = np.linalg.eig(b) print("特征值:",c) print("特征向量:\n",d) print("学号:3008") 结果如下
阅读全文
摘要:import numpy as np a = np.array([[3,1],[1,2],[1,1]]) b = np.array([9,8,6]) x = np.linalg.pinv(a) @ b print(np.round(x,4)) print("学号:3008") 结果如下
阅读全文
摘要:import numpy as np a = np.array([[3,1],[1,2]]) b = np.array([9,8]) x1 = np.linalg.inv(a) @ b x2 = np.linalg.solve(a,b) print(x1);print(x2) print("学号:3
阅读全文
摘要:import numpy as np a = np.array([[0,3,4],[1,6,4]]) b = np.linalg.norm(a,axis = 1) c = np.linalg.norm(a,axis = 0) d = np.linalg.norm(a) print("行向量2范数为:
阅读全文
摘要:import numpy as np a = np.ones(4) b = np.arange(2,10,2) c = a @ b d = np.arange(16).reshape(4,4) f = a @ d g = d @ a print(a);print(b);print(c) print(
阅读全文
摘要:import numpy as np a = np.array([[0,3,4],[1,6,4]]) b = np.array([[1,2,3],[2,1,4]]) c = a / b d = np.array([2,3,2]) e = a * d f = np.array([[3],[2]]) g
阅读全文
摘要:import numpy as np a = np.array([[0,3,4],[1,6,4]]) b = a.sum() c1 = sum(a) c2 = np.sum(a,axis = 0) c3 = np.sum(a,axis = 0,keepdims = True) print(c2.sh
阅读全文
摘要:import numpy as np a = np.arange(16).reshape(4,4) b = np.vsplit(a,2) print('行分割:\n',b[0],'\n',b[1]) c = np.hsplit(a,4) print('列分隔:\n',c[0],'\n',c[1],'
阅读全文
摘要:import numpy as np a = np.arange(16).reshape(4,4) b = np.floor(5 * np.random.random((2,4))) c = np.ceil(6 * np.random.random((4,2))) d = np.vstack([a,
阅读全文
摘要:import numpy as np a = np.arange(16).reshape(4,4) b = a[1][2] c = a[1,2] d = a[1:2,2:3] x = np.array([0,1,2,1]) print(a[x == 1]) print('学号:3008') 结果如下
阅读全文
摘要:import numpy as np a = np.ones(4,dtype = int) b = np.ones((4,),dtype = int) c = np.ones((4,1)) d = np.zeros(4) e = np.empty(3) f = np.eye(3) g = np.ey
阅读全文
摘要:import numpy as np a1 = np.array([1,2,3,4]) a2 = a1.astype(float) a3 = np.array([1,2,3],dtype = float) print(a1.dtype);print(a2.dtype);print(a3.dtype)
阅读全文
摘要:s1 = [str(x) + str(y) for x,y in zip(['v'] * 4,range(1,5))] s2 = list(zip('abcd',range(4))) print(s1);print(s2) print("3008") 结果如下图所示
阅读全文
摘要:def filter_non_unique(L): return [item for item in L if L.count(item) == 1] a = filter_non_unique([1,2,2,3,4,4,5]) print(a) print("学号:3008") 结果如下图所示
阅读全文
摘要:a = filter(lambda x:x > 10,[1,111,2,45,7,6,13]) b = filter(lambda x:x.isalnum(),['abc','xy12','***']) #isalnum()是测试是否为字母或数字的方法 print(list(a));print(li
阅读全文
摘要:import random x = random.randint(1e5,1e8) y = list(map(int,str(x))) z = list(map(lambda x,y:x%2 == 1and y % 2 == 0,[1,3,2,4,1],[3,2,1,2])) print(x);pr
阅读全文
摘要:x1 = "abcde" x2 = list(enumerate(x1)) for ind,ch in enumerate(x1):print(ch) print("学号:3008") 结果如下图
阅读全文
摘要:import numpy.random as nr x1 = list(range(9,21)) nr.shuffle(x1) x2 = sorted(x1) x3 = sorted(x1,reverse = True) x4 = sorted(x1,key = lambda item : len(
阅读全文
摘要:def factorial(n): r = 1 while n > 1: r *= n n -= 1 return r def fib(n): a,b = 1,1 while a < n: print(a,end=' ') a,b = b,a+b print('%d! = %d'%(6,factor
阅读全文
摘要:from math import * a = sin(3) b = pi c = e d = radians(180) print(a);print(b);print(c);print(d) print("学号:3008") 结果如下图
阅读全文
摘要:from random import sample from numpy.random import randint a = sample(range(10),5) b = randint(0,10,5) print(a);print(b) print("学号:3008") 结果如下图
阅读全文
摘要:import math import random import numpy.random as nr a = math.gcd(12,21) b = random.randint(0,2) c = nr.randint(0,2,(4,3)) print(a);print(b);print(c) p
阅读全文
摘要:f = lambda x,y,z:x * y * z L = lambda x :[x**2,x**3,x**4] print(f(3,4,5));print(L(2)) print("学号:3008") 结果如下图
阅读全文
摘要:def bifurcate_by(L,fn): return [[x for x in L if fn(x)], [x for x in L if not fn(x)]] s = bifurcate_by(['beep','boop','foo','bar'],lambda x: x[0] == '
阅读全文
摘要:#定义阶乘函数 def factorial(n): r = 1 while n > 1: r *= n n -= 1 return r def fib(n): a,b = 1,1 while a < n: print(a,end=' ') a,b = b,a+b print('%d! = %d'%(
阅读全文
摘要:import stringimport randomx=string.ascii_letters+string.digitsy=".join([random.choice(x)for i in range(1000)])" #choice()用于从多个元素中随机选择一个d= dict()for ch
阅读全文
摘要:#利用collections模块的Counter()函数直接作出统计 #依次加载三个模块 import string,random,collections x = string.ascii_letters + string.digits y = ''.join([random.choice(x) f
阅读全文
摘要:'''可以对字典对象进行迭代或者遍历,默认是遍历字典的键,如果需要遍历 字典的元素必须使用字典对象的items()方法明确说明,如果需要遍历字典的 值则必须使用字典对象的values()方法明确说明 ''' Dict = {'age':18,'name':'Zheng','sex':'male'}
阅读全文
摘要:'''字典对象提供了一个get()方法用来返回指定键对应的值,并且允许指定键不存在时返回特定的值''' Dict = {'age':18,'sorce':'Zheng','sex':'male'} #输出键对应的值 print(Dict['age']) print(Dict['sorce']) pr
阅读全文
摘要:'''字典用{}标识,它是一个无序的“键(key):值(value)”对集合。 在同一个字典中,键必须是唯一的,但值不必唯一,值可以是任何数据类型, 但键必须是不可变的,如字符串,数字,元组''' #首先需要先定义一个字典 dict1 = {'Alice':'123','Beth':'456','C
阅读全文
摘要:'''集合是一个无序不重复元素的序列,有两种表示方法:1.使用{}2.使用set()函数,使用空集合必须使用set()''' #首先先定义一个集合student ={'Tom','Jim','Mary','Tom','Jack','Rose'} #输出集合studentprint(student)
阅读全文
摘要:T = ('abc',12,3.45,'python',2.789)#输出完整数组print(T)#输出元组的最后一个元素print(T[-1])#输出元组的第二、三元素print(T[1:3])print("学号:3008") T = ('abc',12,3.45,'python',2.789)
阅读全文
摘要:from numpy.random import randint import numpy as np a = randint(10,20,16) ma = max(a) ind1 = [index for index,value in enumerate(a) if value == ma] in
阅读全文
摘要:''''先遍历列表中嵌套的子列表,然后再遍历子列表的元素并提取出来作为最终列表中的元素'''a=[[1,2,3],[4,5,6],[7,8,9]]d=[c for b in a for c in b]print(d)print("学号:3008") a=[[1,2,3],[4,5,6],[7,8,9
阅读全文
摘要:'''首先先定义一个列表,列表是写在[]里,用逗号隔开的,元素是可以改变的列表的截取语法结构是:变量[头下标:尾下标]'''L = ['abc',12,3.45,'python',2.789]#输出完整列表print(L)#输出列表的第一个元素print(L[0])#将列表的第一个元素修改为‘a’L
阅读全文
摘要:import numpy as np a = [] with open('data2_2.txt') as f: for(i,s) in enumerate(f): a.append([a.count('a'),a.count('c'), a.count('g'),a.count('t')]) b
阅读全文
摘要:python中字符串用单引号或者双引号括起来 访问字符串时,采用方式: 变量[头下标:尾下标] str1= "Hello word!" print(str1) print(str1[0:-1]) print(str1[-1]) print(str1[2:5]) print(str1[2:]) pri
阅读全文
摘要:import matplotlib.pyplot as plt import numpy as np import cvxpy as cp x=cp.Variable(6,pos=True) obj=cp.Minimize(x[5]) a1=np.array([0.025, 0.015, 0.055
阅读全文
摘要:initial_costs = [2.5, 2.6, 2.8, 3.1] salvage_values = [2.0, 1.6, 1.3, 1.1] maintenance_costs = [0.3, 0.8, 1.5, 2.0] dp = [[float('inf')] * 2 for _ in
阅读全文
摘要:import heapq def prim(graph, start): num_nodes = len(graph) visited = [False] * num_nodes min_heap = [(0, start, -1)] mst_cost = 0 mst_edges = [] whil
阅读全文
摘要:edges = [ ("Pe", "T", 13), ("Pe", "N", 68), ("Pe", "M", 78), ("Pe", "L", 51), ("Pe", "Pa", 51), ("T", "N", 68), ("T", "M", 70), ("T", "L", 6
阅读全文
摘要:import numpy as np demands = [40, 60, 80] max_production = 100 total_demand = sum(demands) dp = np.full((4, total_demand + 1), float('inf')) dp[0][0]
阅读全文
摘要:import numpy as np from scipy.optimize import minimize def objective(x): return 2*x[0] + 3*x[0]**2 + 3*x[1] + x[1]**2 + x[2] def constraint1(x): retur
阅读全文
摘要:import numpy as np from scipy.optimize import minimize # 定义目标函数 def objective(x): return -np.sum(np.sqrt(x)) # 注意:scipy的minimize默认是最小化问题,所以这里取负号 # 定义约
阅读全文