这是朋友写的
#(1)去掉alist里面的重复元素
alist = [1, 'a', 2, 'a', 3, 'acd', 4, 1]
print(set(alist ))
#(2)找出字符串中所有的数字(如果是连续数字,则返回一个数)
import re
s = 'xiangtan2020university2021'
pat = '\d+'
out = re.compile('\d+').findall(s)
print(out)
#(3)编写万有引力公式,SI单位制
G=6.67*10e-11
def wanyouyinli(M,m,r):
F = G*M*m/(r*r)
print("两物体间的万有引力为:",F,end="")
print("N")
M = float(input("请输入第一个物体质量M的值"))
m = float(input("请输入第二个物体质量m的值"))
r = float(input("请输入两个物体之间的距离r的值"))
wanyouyinli(M,m,r)
#(4)创建一个值域范围从10到49的向量
import numpy as np
Z = np.arange(10, 50)
print (Z)
# (5)创建一个 8x8 的随机数组并找到它的最大值和最小值
import numpy as np
Z = np.random.random((8, 8))
Zmax, Zmin = np.max(Z), np.min(Z)
print (Zmax, Zmin)
#(6)创建一个长度为30的随机向量并找到它的平均值和中值
import numpy as np
Z = np.random.random(30)
mean = np.mean(Z)
words = Z[15]
print (mean)
print(words)
#(7) 请找到合适的函数,拟合曲线(xdata, ydata),给出拟合参数的误差,并将拟合数据和拟合函数可视化。
import matplotlib.pyplot as plt
import numpy as np
xdata = [-2.0, -1.78947368, -1.57894737, -1.36842105, -1.15789474, -0.94736842,
-0.73684211, -0.52631579, -0.31578947, -0.10526316, 0.10526316, 0.31578947,
0.52631579, 0.73684211, 0.94736842, 1.15789474, 1.36842105, 1.57894737, 1.78947368, 2.0]
ydata = [39.04610383, 27.79558807, 20.21653958, 16.87369791, 10.07887526, 8.42543855,
6.57355117, 3.62983023, 4.26805214, 2.13979637, -0.27302139, 2.42334219, -1.44759013,
2.92733343, 2.68164025, 1.10441227, -1.820398, 0.9003836, 0.35316656, 0.65541194]
xdata = np.array(xdata)
ydata = np.array(ydata)
poly = np.polyfit(xdata, ydata, 19)
y = np.polyval(poly, xdata)
err = (y - ydata)/ydata
y1 = ''
for i in range(len(poly)):
y1 += '({0}x**{1})+'.format(poly[i],len(poly)-1-i)
print('公式为: y={}'.format(y1))
print('误差为: {0}'.format(err.mean()))
plt.plot(xdata, ydata,'k-', label = 'raw data')
plt.plot(xdata, y, 'r--', label = 'fit data')
plt.legend()
plt.show()
#(8) 已知一个小球初始时刻在0点,并做水平随机运动,每秒等概率左移或右移的长度为1,请画出时间t与小球位置的函数图像。
import random
import matplotlib.pyplot as plt
time = 100
position = [0]
step = []
for i in range(time):
step.append(random.choice([-1, 1]))
position.append(position[i] + step[i])
fig = plt.figure()
x = range(0, time + 1)
y = position
plt.plot(x,y,'.-b')
plt.show()
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)