2.2
点击查看代码
from scipy.special import gamma
import pylab as plt
import numpy as np
plt.rc('text',usetex = True)
x=np.linspace(-5,5,1000)
plt.plot(x,gamma(x),c='k')
plt.xlabel('$x$')
plt.ylabel('$\Gamma(x)$');plt.show()
点击查看代码
L=['abc',12,3.45,'Python',2.789]
print(L)
print(L[0])
L[0] = 'a'
L[1:3]=['b','Hello']
print(L)
L[2:4] = []
print(L)
print("学号:2023310143010")
点击查看代码
a=[[1,2,3],[4,5,6],[7,8,9]]
d=[c for b in a for c in b]
print(d)
点击查看代码
'''
#(1)列出文件夹下所有exe和py文件
import os
fn=[filename for filename in
os.listdir('C:/Users/setup/.spyder-py3/python数学建模')
if filename.endswith(('.exe','.py'))]
print(fn)
print("学号:2023310143010")
'''
#(2)用列表推导式查找数组中最大元素的所有位置
from numpy.random import randint
import numpy as np
a = randint(10,20,16)
ma = max(a)
indl = [index for index,value in enumerate(a) if value==ma]
ind2=np.where(a==ma)
print(indl);print(ind2[0])
print("学号:2023310143010")
2.7
student = {'Tom','Jim','Mary','Tom','Jack','Rose'}
print(student)
a = set('abcdabc')#设置空集合用set(),它可将列表转换为集合
print(a)
2.8
dict1={'Alice':'123','Beth':'456','Cecil':'abc'}
print(dict1['Alice'])
dict1['new']='Hello'
dict1['Alice']='1234'
dict2 = {'abc':123,456:78.9}
print(dict2[456])
2.9
Dict= {'age':18,'score':[98,97],'name':'Zhang','sex':'male'}
print(Dict['age'])
print(Dict.get('age'))
print(Dict.get('address','Not Exists'))
print(Dict['address'])
2.10
Dict= {'age':18,'score':[98,97],'name':'Zhang','sex':'male'}
for item in Dict:
print(item)
print('-----------')
for item in Dict.items():
print(item)
print('-----------')
for value in Dict.values():
print(value)
2.11
import string
import random
x = string.ascii_letters+string.digits
y=''.join([random.choice(x) for i in range(1000)])
d=dict()
for ch in y:
d[ch] = d.get(ch,0)+1
for k,v in sorted(d.items()):
print(k,':,v')
import string,random,collections
x = string.ascii_letters+string.digits
y=''.join([random.choice(x) for i in range(1000)])
count = collections.Counter(y)
for k,v in sorted(count.items()):
print(k,':,v')
2.12
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'%(5,factorial(5)))
fib(3)
2.13
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','boo'],lambda x:x[0]=='b')
print(s)
2.14
f = lambda x, y,z:xyz
L = lambda x:[x2,x3,x**4]
print(f(3,4,5));print(L(2))
2.15
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)
2.16
from random import sample
from numpy.random import randint
a = sample(range(10),5)#在【0,9】区间上选择不重复的5个整数
b = randint(0,10,5)#在【0,9】区间上生成5个随机整数
print(a);
print(b)
2.17
from math import *
a = sin(3)
b = pi
c = e
d = radians(180)#把角度转化为弧度
print(a);print(b);print(c);print(d)
2.18
from ex2_12_2 import *
print(factorial(6))
fib(300)
2.19
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(str(item)))
print(x1);print(x2);print(x3);print(x4)
2.20
x1="abcde"
x2=list(enumerate(x1))
for ind,ch in enumerate(x1):print(ch)
2.21
import random
x = random.randint(1e5,1e8)
y = list(map(int,str(x)))
z = list(map(lambda x,y:x%21 and y%20,[1,3,2,4,1],[3,2,1,2]))
print(x);print(y);print(z)
2.22
a=filter(lambda x: x>10,[1,11,2,45,7,6,13])
b=filter(lambda x:x.isalnum(),['abc','xy12','***'])
isalnum是测试是否为字母或数字的方法
print(list(a));print(list(b))
2.23
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)
2.24
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)
2.25
import numpy as np
a1=np.array([1,2,3,4])
a2=a1.astype(float)
a3=np.array([1,2,3,4],dtype=float)
print(a1.dtype);print(a2.dtype);print(a3.dtype)
b=np.array([[1,2,3],[4,5,6]])
c=np.arange(1,5)
d=np.linspace(1,4,4)
e=np.logspace(1,3,3,base=2)
2.26
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.eye(3,k=1)
h = np.zeros_like(a)
print(a);print(b);print(c);print(d);print(e);print(f);print(g);print(h);
2.27
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]
f = np.array([0,1,2,1])
print(a);print(b);print(c);print(d);print(f);
2.28
import numpy as np
a = np.arange(16).reshape(4,4)
b = np.floor(5np.random.random((2,4)))
c = np.ceil(6np.random.random((4,2)))
d = np.vstack([a,b])
e = np.hstack([a,c])
print(a);print(b);print(c);print(d);print(e);
2.29
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],'\n',c[2],'\n',c[3])
2.30
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.shape,c3.shape)
2.31
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 = ad
f = np.array([[3],[2]])
g = af
h = a**(1/2)
print(a);print(b);print(c);print(d);print(e);print(f);print(g);print(h);
2.32
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(d);print(f);print(g)
2.33
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.linslg.norm(a)
print('行向量2范数为:',np.round(b,4))
print('列向量2范数为:',np.round(c,4))
print('矩阵2范数为:',round(d,4))
2.34
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)
2.35
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))
2.36
import numpy as np
a = np.eye(4)
b = np.rot90(a)
c,d = np.linalg.eig(b)
print('特征值为:',c)
print('特征向量为:\n',d)
2.37
import pandas as pd
import numpy as np
dates = pd.date_range(start = '20191101',end = '20191124',freq = 'D')
a1 = pd.DataFrame(np.random.randn(24,4),index = dates,columns = list('ABCD'))
a2 = pd.DataFrame(np.random.rand(24,4))
print(a1);print(a2)
2.38
import pandas as pd
import numpy as np
dates = pd.date_range(start = '20191101',end = '20191124',freq = 'D')
a1 = pd.DataFrame(np.random.randn(24,4),index = dates,columns = list('ABCD'))
a2 = pd.DataFrame(np.random.rand(24,4))
a1.to_excel('data2_38_1.xlsx')
a2.to_csv('data2_38_2.csv')
f = pd.ExcelWriter('data2_38_3.xlsx')
a1.to_excel(f,"Sheet1")
a2.to_excel(f,"Sheet2")
f.save()
2.39
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))
2.40
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,d2])
s1 = d.groupby('A').mean()
s2 = d.groupby('A').apply(sum)
2.41
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.iloc['a','one'] = np.nan
b = a.iloc[1:3,0:2].values
a['four'] = 'bar'
a2 = a.reindex(['a','b','c','d','e','f'])
a3 = a2.dropna()
2.42
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]
print(L1);print(L2)
with open('data2_42.txt','w')as fp2:
fp2.writelines(data)
2.43
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')
c = np.loadtxt("data2_43_2.csv",delimiter = ',')
2.44
from scipy.optimize import fsolve,root
fx = lambda x: x980-5.01*x979+7.398x**978-3.388x977-x3+5.01x**2-7.398x+3.388
x1 = fsolve(fx,1.5,maxfev = 4000)
x2 = root(fx,1.5)
print(x1,'\n','-----------');print(x2)
2.45
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)
2.46
from scipy.integrate import quad
def fun46(x,a,b):
return ax**2+bx
I1 = quad(fun46,0,1,args = (2,1))
I2 = quad(fun46,0,1,args = (2,10))
print(I1);print(I2)
2.47
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+(y0-x[1])2)-d
s = least_squares(fx,np.random.rand(2))
print(s,'\n','-------','\n',s.x)
2.48、
点击查看代码
from scipy.sparse.linalg import eigs
import numpy as np
a = np.array([[1,2,3],[2,1,3][3,3,6]],dtype=float)
b,c = np.linalg.eig(a)
d,e = eigs(a,1)
print('最大模特征值:',d)
print('对应的特征向量为:\n',e)
点击查看代码
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)
点击查看代码
import sympy as sp
sp.var('x1,x2')
s = sp.solve([x1**2+x2**2-1,x1-x2],[x1,x2])
print(s)