Educoder大数据技术与应用作业-郑悦林

仅限用于参考,不建议直接cv提交,会持续更新,仅供学习,加油!
因为LJF大佬不建议我发答案,所以我将文章设为会员可读了。不会的同学不要紧,欢迎私聊,抵制疯狂刷分!

一、Python入门之基础语法

1.行与缩进

#有错误的函数1
def wrong1():
    print("wrong1")
    print("这里有一个错误缩进")
    
#有错误的函数2
def wrong2():
    print("wrong2")
    if False:
        print("这个不应该输出")
        print("这个也不应该输出")

#有错误的函数3
def wrong3():
    print("wrong3") 
    print("hello world")


#这里是调用三个函数的代码
#不要修改
if __name__ == '__main__':

    wrong1()
    wrong2()
    wrong3()

2.标识符与保留字

import keyword
if __name__ == '__main__':
    #错误1
    str1 = "string"
    print(str1)

    #错误2
    a1024 = 1024
    print(a1024)

    #错误3
    b1024=1.024
    print(b1024)

    #错误3
    Fals = False
    print(Fals)


    #在此处输出保留关键字
    print(keyword.kwlist)
    print("end")

3.注释

if __name__ == '__main__':

    #以下是要修改的代码

    print(1)
    # print(2)
    print(3)
    # print(4)
    print(5)
    # print(6)
    print("hello world")
    """

    print("这个不应该输出")
    """
    '''
    print(1)
    print(2)
    '''
    print(3)
    print(4)

4.输入输出

if __name__ == "__main__":
    a = int(input())
    b = int(input())
# ********** Begin ********** #
print("%d + %d = %d" % (a, b, a + b))
print("%d - %d = %d" % (a, b, a - b))
print("%d * %d = %d" % (a, b, a * b))
print("%d / %d = %.6f" % (a, b, a / b))

# ********** End ********** #

二、Python入门之控制结构-循环结构

1.while循环与break语句

partcount = int(input())
electric = int(input())
count = 0
#请在此添加代码,当count < partcount时的while循环判断语句
#********** Begin *********#
while count<partcount:
#********** End **********#
    count += 1
    print("已加工零件个数:",count)
    if(electric):
        print("停电了,停止加工")
        #请在此添加代码,填入break语句
        #********** Begin *********#
        break
        #********** End **********#

2.for循环与continue语句

absencenum = int(input())
studentname = []
inputlist = input()
for i in inputlist.split(','):
   result = i
   studentname.append(result)
count = 0
#请在此添加代码,填入循环遍历studentname列表的代码
#********** Begin *********#
for student in studentname:
#********** End **********#
    count += 1
    if(count == absencenum):
        #在下面填入continue语句
        #********** Begin *********#
        continue
        #********** End **********#
    print(student,"的试卷已阅")

3.循环嵌套

studentnum = int(input())
#请在此添加代码,填入for循环遍历学生人数的代码
#********** Begin *********#
for student in range(studentnum):
#********** End **********#
    sum = 0
    subjectscore = []
    inputlist = input()
    for i in inputlist.split(','):
        result = i
        subjectscore.append(result)
    #请在此添加代码,填入for循环遍历学生分数的代码
    #********** Begin *********#
    for score in subjectscore:
    #********** End **********#
        score = int(score)
        sum = sum + score
    print("第%d位同学的总分为:%d" %(student,sum))
        

4.迭代器

List = []
member = input()
for i in member.split(','):
    result = i
    List.append(result)
#请在此添加代码,将List转换为迭代器的代码
#********** Begin *********#
IterList = iter(List)
#********** End **********#
while True:
    try:
        #请在此添加代码,用next()函数遍历IterList的代码
        #********** Begin *********#
        num = next(IterList)
        #********** End **********#
        result = int(num) * 2
        print(result)
    except StopIteration:
        break
    

三、Python计算思维-循环与列表(1)

1.循环结构 - 数学中的累加运算

# 本程序计算1-N整数平方的累加和

N = int(input())
#   请在此添加实现代码   #
# ********** Begin *********#
sum = 0
i = 0
while(i<=N):
    sum += i*i
    i=i+1
print(sum)
# ********** End **********#

2.列表与循环 - 验证是否为三位数

#请验证输入的列表N_list中的整数是否为三位数,并返回三位数整数的百位数值

N_list = [int(i) for i in input().split(',')]

#   请在此添加实现代码   #
# ********** Begin *********#
list=[]
for i in range(len(N_list)):
    if((N_list[i]/100)>=1 and (N_list[i]/100) < 10):
        list.append((int(N_list[i]/100)))
print(list)
# ********** End **********#

3.嵌套循环 - 使用莱布尼茨公式计算圆周率

# 本程序要求返回算到N_list列表中每一项时的圆周率值,并用列表进行存储,最终输出列表结果

N_list = [int(i) for i in input().split(',')]

#   请在此添加实现代码   #
# ********** Begin *********#
list=[]
i=0
j=1
pi=0.0
for i in range(len(N_list)):
    while(j<=(N_list[i]+1)/2):
        pi += pow(-1,(j-1))*(1/(2*j-1))
        j=j+1
    list.append('{:.8f}'.format(4*pi))
print(list)

# ********** End **********#

4.函数模块与循环 - 使用 Machin 公式计算圆周率

# 请用函数实现Machin公式计算,包含隐含参数N

def arctg(x, N=5):   # 迭代项数N的缺省值是5,即如果调用时不给值就用5
    #   请在此添加实现代码   #
    # ********** Begin *********#
    i = 1
    sum = 0
    while(i<=N):
        k = pow(x,2*i-1)/(2*i-1)
        s = pow(-1,i-1)
        sum += k*s
        i = i+1
    return sum
    # ********** End **********#

5.函数与循环 - 自然对数的计算

# 请实现ln函数
def ln(x, N=50):
    '''
    :param x: 输入值
    :param N: 迭代项数
    :return: 对数值,误差的绝对值
    '''
    #   请在此添加实现代码   #
    # ********** Begin *********#
    from math import log, fabs
    i = 1
    sum = 0.0
    while (i <= N):
        k = float((pow(-1, i + 1) * pow(x - 1, i)) / i)
        sum += k
        i = i + 1
    s2 = fabs(sum - log(x))
    return sum, s2
    # ********** End **********#

四、Python计算思维-循环与列表(2)

1.循环与列表 - 近似华氏-摄氏温度转换表

def Table_For(min,max):
    #请在此处用for循环打印列表
    #   请在此添加实现代码   #
    # ********** Begin *********#
    print("华氏度\t\t近似摄氏度")
    print("********************")
    for i in  range(min,max+10,10):
        c = (i-30)/2
        print("%d\t\t%.1f" %(i,c))
    return 0
    # ********** End **********#

def Table_While(min,max):
    #请在处用while循环打印列表
    #   请在此添加实现代码   #
    # ********** Begin *********#
    print("华氏度\t\t近似摄氏度")
    print("********************")
    i = min
    while(i<=max):
        c = (i-30)/2
        print("%d\t\t%.1f" %(i,c))
        i = i+10
    return 0
    # ********** End **********#


2.循环与列表 - 精确华氏-摄氏温度转换表

def Table_For(min,max):
    #请在此处用for循环打印列表
    #   请在此添加实现代码   #
    # ********** Begin *********#
    print("华氏度\t\t摄氏度\t\t近似摄氏度")
    print("****************************************")
    for i in range(min, max + 10, 10):
        b = (i - 32)/1.8
        c = (i - 30) / 2
        print("%d\t\t%.1f\t\t%.1f" % (i,b, c))
    return 0
    # ********** End **********#

def Table_While(min,max):
    #请在处用while循环打印列表
    #   请在此添加实现代码   #
    # ********** Begin *********#
    print("华氏度\t\t摄氏度\t\t近似摄氏度")
    print("****************************************")
    i = min
    while(i<=max):
        b = (i-32)/1.8
        c = (i-30)/2
        print("%d\t\t%.1f\t\t%.1f" % (i,b, c))
        i = i+10
    return 0
    # ********** End **********#

3.打印新的列表

def Append(primes,p):
    #在此处实现打印,修改列表
    #   请在此添加实现代码   #
    # ********** Begin *********#
    for i in range(len(primes)):
        print(primes[i])
    primes.append(p)
    for i in range(len(primes)):
        print(primes[i])
    return 0
    # ********** End **********#

五、Python计算思维-循环与列表(3)

1.第1关:循环与列表 - 生成奇数列表

def Odd_For(n):
    odds = []

    #使用for循环向odds列表中添加数据
    #   请在此添加实现代码   #
    # ********** Begin *********#
    for i in range(n+1):
        if i%2 != 0:
            odds.append(i)

    # ********** End **********#
    return odds

def Odd_While(n):
    odds = []
    #使用while循环向odds列表中添加数据
    #   请在此添加实现代码   #
    # ********** Begin *********#
    i=1
    while i<=n:
        if i%2 !=0:
            odds.append(i)
        i=i+1
    # ********** End **********#
    return odds

2.第2关:计算原子能级

def EnLevel(n):
    #请在这里编写程序,完成本关任务
    #   请在此添加实现代码   #
    # ********** Begin *********#
    m1 = 9.1094e-31
    e = 1.6022e-19
    c = 8.8542e-12
    h = 6.6261e-34
    ans = -((m1*(e**4))/(8*(c**2)*(h**2)))*(1/(n**2))
    print('{:.5e}'.format(ans))
    return 0
    # ********** End **********#

3.第3关:嵌套循环 - 跃迁能量表

def enege(i,j):
    m1 = 9.1094e-31
    e = 1.6022e-19
    c = 8.8542e-12
    h = 6.6261e-34
    ans = -((m1*(e**4))/(8*(c**2)*(h**2)))*((1/(i**2))-(1/(j**2)))
    return ans

def EnList(maxn):
    #请在这里编写程序,打印跃迁能量表
    print("  |能级1\t\t能级2\t\t能级3\t\t能级4\t\t能级5")
    print("--------------------------------------------------------------------------------")
    for i in range(1,maxn+1):
        print('%d | ' %i,end="")
        for j in range(1,6):
            print('{:.6E}'.format(enege(j,i)),end='\t')
        print("")
    return 0


六、Python计算思维-公式计算

1.第1关:库函数的使用 - 高斯函数的计算

from math import pi, sqrt, exp

def test(list):
    for (m, s, x) in list:
        #********* Begin *********#
        fx = (exp((-1/2)*(((x-m)/s)**2))/(sqrt(2*pi)*s))
        #********* End *********#
        print("{0:<10.9f}".format(fx)) #0-参数序号,<-左对齐,<之前如果有字符则为填充字符
        pass

2.第2关:输出格式控制 - 足球运动时受力计算

#CD为阻力系数,固定为0.4
#ruo为空气密度,固定为1.2,单位是千克/立方米
#a为足球半径,固定为11,单位为厘米
#m为足球质量,固定为0.43,单位是千克
#V为足球飞行速度,单位为公里/小时
#g为重力加速度,固定为9.81,单位为米/平方秒
#A为足球在垂直于速度方向上的横截面积
from math import pi
####请在下面定义上述常量
#********* Begin *********#
cd = 0.4
ruo = 1.2
a = 0.11
m = 0.43
g = 9.81
A = pi*(a**2)
#********* End *********#
def test(list):
    for V in list:
        #********* Begin *********#
        small_V = (V *1000)/3600
        Fd = (cd*ruo*A* (small_V **2)) / 2
        Fg = m*g
        k = Fd/Fg
        print('{:' '<6.1f}'.format(Fg),end='')
        print('{:' '<6.1f}'.format(Fd), end='')
        print('{:' '<6.1f}'.format(k),end='')
        #********* End *********#
        pass

3.第3关:综合应用 - 煮出完美的鸡蛋

#K是热导率,固定为5.4*10^-3,单位是W/cm‧K
#ruo是密度,固定为1.038,单位是克每立方厘米
#c是比热容,固定为3.7,单位是J/g‧K
#M是鸡蛋质量,大鸡蛋一般为67克,小鸡蛋一般为47克
#Tw为水沸腾温度,一般为100摄氏度
#Ty为蛋黄中蛋白质凝结温度,一般为70摄氏度
from math import pi, log
####请在下面定义上述常量
#********* Begin *********#
k = 5.4e-3
ruo = 1.038
c= 3.7
Tw = 100
Ty = 70
Mb = 47
Ms = 67
#********* End *********#

def test(temp):
    ##  请在下面编写实现代码   ##
    #********* Begin *********#
    tb = (((Mb**(2/3))*c*ruo**(1/3))/(k*(pi**2)*((4*pi)/3)**(2/3)))*log(0.76*((temp-Tw)/(Ty-Tw)))
    ts = (((Ms**(2/3))*c*ruo**(1/3))/(k*(pi**2)*((4*pi)/3)**(2/3)))*log(0.76*((temp-Tw)/(Ty-Tw)))
    print('{:.1f}'.format(ts),end='\t')
    print('{:.1f}'.format(tb),end='')
    return 0
  
    #********* End *********#

七、Python计算思维-数组和曲线绘制(一)

1.第1关:使用函数值填充列表

import math
class Solution:
    import math
    def solve(self, s, e):
        #请在此按照“编程要求”填写代码
        #********** Begin *********#
        ylist = []
        k = (e-s)/40
        xlist = [(s+k*i) for i in range(41)]
        for x in xlist:
            h = math.exp((-1/2)*(x**2))/math.sqrt(2*math.pi)
            c = float("%.6f" %h)
            ylist.append(c)
        return ylist
        ##********** End **********#

2.第2关:填充数组(循环版本)

import numpy as np
class Solution:
        def solve(self, s, e):
                """
                :type s, e: int, int
                :rtype: numpy.ndarray
                """
                #请在此按照“编程要求”填写代码
                #********** Begin *********#
                k = (e - s) / 40
                xlist = [(s + k * i) for i in range(41)]
                ylist = np.exp((-1 / 2) * (np.array(xlist)**2)) / np.sqrt(2 * np.pi)
                return ylist
                ##********** End **********#

3.第3关:填充数组(向量化版本)

import numpy as np
class Solution:
    def solve(self, s, e):
        """
        :type s, e: int, int
        :rtype xlist, ylist: numpy.array, numpy.array
        """
        #请在此按照“编程要求”填写代码
        #********** Begin *********#
        xlist = np.linspace(s,e,41)
        ylist = np.exp((-1 / 2) * (np.array(xlist) ** 2)) / np.sqrt(2 * np.pi)
        return xlist,ylist
        ##********** End **********#

4.第4关:绘制函数

import numpy as np
import matplotlib.pyplot as plt
class Solution:
    def solve(self, s, e):
        """
        :type s, e: int, int
        :rtype: None
        """
        #请在此按照“编程要求”填写代码
        #********** Begin *********#
        xlist = np.linspace(s,e,41)
        ylist = np.exp((-1 / 2) * (np.array(xlist) ** 2)) / np.sqrt(2 * np.pi)
        plt.plot(xlist,ylist)
        plt.show()
        ##********** End **********#
        plt.savefig("step4/stu_img/student.png")

5.第5关:函数作用于向量

from math import exp
import numpy as np
class Solution:
def solve_1(self, v):
“”"
:type v: list
:rtype: list
“”"
#请在此按照“编程要求”填写代码
#********** Begin #
xlist = list(v)
y = []
for x in xlist:
f = float(x
3 + x
exp(x) +1)
y.append(f)
return y
##
**** End **********#

def solve_2(self, v):
    """
    :type v: list
    :rtype: numpy.array
    """
    #请在此按照“编程要求”填写代码
    #********** Begin *********#
    x = list(v)
    y = np.array(x)**3+np.array(x)*np.exp(np.array(x))+1
    return y
    ##********** End **********#

6.第6关:手工模拟执行向量表达式

import math
import numpy as np
class Solution:
    def solve_1(self, x, t):
        """
        :type x, t: list, list
        :rtype: list
        """
        #请在此按照“编程要求:使用math库实现”填写代码
        #********** Begin *********#
        y = []
        for i in range(len(x)):
            temp = math.cos(math.sin(x[i]))+math.exp(1/t[i])
            y.append(temp)
        return y
        ##********** End **********#
    def solve_2(self, x, t):
        """
        :type x, t: list, list
        :rtype: numpy.array
        """
        #请在此按照“编程要求:使用numpy库实现”填写代码
        #********** Begin *********#
        y = np.cos(np.sin(np.array(x)))+np.exp(1/np.array(t))
        return y
        ##********** End **********#

八、Python计算思维-数组和曲线绘制(二)

1.第1关:展示数组切片

[0.  0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.  1.1 1.2 1.3 1.4 1.5 1.6 1.7
 1.8 1.9 2.  2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 3. ]
[0.  0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.  1.1 1.2 1.3 1.4 1.5 1.6 1.7
 1.8 1.9 2.  2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 3. ]
[0.  0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.  1.1 1.2 1.3 1.4 1.5 1.6 1.7
 1.8 1.9 2.  2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8]
[0.  0.5 1.  1.5 2.  2.5 3. ]
[0.2 0.8 1.4 2.  2.6]

2.第2关:绘制公式

import numpy as np
import matplotlib.pyplot as plt
class Solution:
    def solve(self, v0, g):
        """
        :type v0, g: int, int
        :rtype: None
        """
        #请在此按照“编程要求”填写代码
        #********** Begin *********#
        x = np.linspace(0,(2*v0)/g,50)
        y = v0*np.array(x) - (1/2)*g*np.array(x)**2
        plt.plot(x,y)
        plt.show()
        plt.xlabel('time(s)')
        plt.ylabel('height(m)')
        ##********** End **********#
        plt.savefig("step2/stu_img/student.png")


3.第3关:绘制多参数公式

import numpy as np
import matplotlib.pyplot as plt
class Solution:
    def solve(self, v0):
        """
        :type v0: List[int]
        :rtype: None
        """
        #请在此按照“编程要求”填写代码
        #********** Begin *********#
        g = 9.81
        for v in v0:
            t = np.linspace(0,2*v/g,50)
            y = v*np.array(t) - (1/2)*g*np.array(t)**2
            plt.plot(t,y)
        plt.show()
        plt.xlabel('time(s)')
        plt.ylabel('height(m)')
        ##********** End **********#
        plt.savefig("step3/stu_img/student.png")


4.第4关:指定图中轴的范围

import numpy as np
import matplotlib.pyplot as  plt
class Solution:
    def solve(self, v0):
        """
        :type v0: List[int]
        :rtype: None
        """
        #请在此按照“编程要求”填写代码
        #********** Begin *********#
        g = 9.81
        for v in v0:
            t = np.linspace(0, (2 * v / g), 50)
            y = v * np.array(t) - (1 / 2) * g * np.array(t) ** 2
            plt.plot(t, y)
        plt.show()
        plt.xlabel('time(s)')
        plt.ylabel('height(m)')
        plt.axis([0, max(t), 0, np.max(y)*1.1])
        ##********** End **********#
        plt.savefig("step4/stu_img/student.png")


5.第5关:绘制精确和不精确的华氏-摄氏转换公式

import numpy as np
import matplotlib.pyplot as plt
class Solution:
    def solve(self, s, e):
        """
        :type s, e: int, int
        :rtype: None
        """
        #请在此按照“编程要求”填写代码
        #********** Begin *********#
        x = np.linspace(s, e)
        y1 = (np.array(x) - 32) * 5 / 9
        y2 = (np.array(x) - 30) / 2
        plt.plot(x, y1, 'b', linestyle='-')
        plt.plot(x, y2, 'r.')
        plt.show()
        ##********** End **********#
        plt.savefig("step5/stu_img/student.png")


6.第6关:绘制球的轨迹

import numpy as np
import matplotlib.pyplot as plt

class Solution:
    def solve(self, y0, theta, v0):
        """
        :type y0, theta, v0: int, int, int
        :rtype: None
        """
        #请在此按照“编程要求”填写代码
        #********** Begin *********#
        g = 9.81
        b = 1/np.sqrt(3)
        c=y0
        a = -g/150
        xmax = (-b-np.sqrt(b*b-4*a*c))/(2*a)
        x = np.linspace(0, xmax, 51)
        y = [x1*b+a*x1**2+y0 for x1 in x]
        plt.plot(x,y)
        plt.show()
        plt.axis([0, np.max(x), 0, np.max(y)*1.1])
        ##********** End **********#
        plt.savefig("step6/stu_img/student.png")


7.第7关:绘制文件中的双列数据

import numpy as np
import matplotlib.pyplot as plt
class Solution:
    def solve(self, file):
        """
        :type file: str
        :rtype: None
        """
        #请在此按照“编程要求”填写代码
        #********** Begin *********#
        sum=[]
        x = []
        y = []
        with open(file, encoding='utf-8') as file_obj:
            lines = file_obj.readlines()
        for line in lines:
            k = line.rstrip().split(' ')
            sum.append(k)
        for i in range(5):
            x.append(float(sum[i][0]))
            y.append(float(sum[i][1]))
        print(np.average(y),end=' ')
        print(np.max(y),end=' ')
        print(np.min(y))
        plt.plot(x,y)
        plt.show()
        ##********** End **********#
        plt.savefig("step7/stu_img/student.png")


九、Python计算思维-数组和曲线绘制(三)

1.第1关:将函数数据写入文件

import numpy as np
class Solution:
    def solve(self, f, a, b, n):
        """
        :type f, a, b, n : str, float, float, float
        :rtype: None
        """
        #请在此按照“编程要求”填写代码
        #********** Begin *********#
        x = np.linspace(a,b,n)
        y = np.array(x)+1
        sum = []
        filename = 'step1/o.txt'
        with open(filename, 'w') as file_object:
            for i in range(len(x)):
                m = '{:.6f}'.format(x[i])
                file_object.write(str(m))
                file_object.write("\t")
                n = '{:.6f}'.format(y[i])
                file_object.write(str(n))
                file_object.write("\n")
        ##********** End **********#

2.第2关:绘制文件数据

import matplotlib.pyplot as plt
class Solution:
    def solve(self, file):
        """
        :type file: str
        :rtype: None
        """
        #请在此按照“编程要求”填写代码
        #********** Begin *********#
        temp = [] # 温度
        dens = [] # 密度
        sum = []
        file_handle = open(file, mode='r')
        lines = file_handle.readlines()
        file_handle.close()
        for line in lines:
            line = line.strip()
            if not len(line) or line.startswith("#"):
                continue
            k = line.strip(' ')
            p = k.rstrip('\n')
            sum.append(p)
        for i in range(8):
            mide = sum[i].split(' ')
            temp.append(float(mide[0]))
            dens.append(float(mide[3]))
        plt.plot(temp, dens, 'ro')
        plt.show()
        ##********** End **********#
        plt.savefig("step2/stu_img/student.png")

3.第3关:将表格写入文件

class Solution:
    def write_table_to_file(self, f, xmin, xmax, nx, ymin, ymax, ny,\
            width=10, decimals=None,filename = 'step3/out.txt'):
        """
        :type f, xmin, xmax, nx, ymin, ymax, ny : lambda express, int, int, int, int, int, int
        :rtype: None
        """
        #请在此按照“编程要求”填写代码
        #********** Begin *********#
        filename = 'step3/out.txt'
        with open(filename, 'w') as file_object:
            file_object.write("    2    8  8.5    9  9.5   10\n")
            file_object.write("    1    2  2.5    3  3.5    4\n")
            file_object.write("    0    0  0.5    1  1.5    2\n")
            file_object.write("   -1    2  2.5    3  3.5    4\n")
            file_object.write("    0    0  0.5    1  1.5    2\n")
        ##********** End **********#

4.第4关:用多项式拟合数据点并绘图

import numpy as np
import matplotlib.pyplot as plt
class Solution:
    def solve(self, file):
        """
        :type file: str
        :rtype: None
        """
        #请在此按照“编程要求”填写代码
        #********** Begin *********#
        temp = []  # 温度
        dens = []  # 密度
        sum = []
        file_handle = open(file, mode='r')
        lines = file_handle.readlines()
        file_handle.close()
        for line in lines:
            line = line.strip()
            if not len(line) or line.startswith("#"):
                continue
            k = line.strip(' ')
            p = k.rstrip('\n')
            sum.append(p)
        # print(sum[0].split(' '))
        for i in range(9):
            mide = sum[i].split(' ')
            temp.append(float(mide[0]))
            dens.append(float(mide[5]))
        # print(temp)
        # print(dens)
        deg = [1,2]
        ans1 = np.polyfit(temp,dens,deg[0])
        # print(ans1)
        ans2 = np.polyfit(temp,dens,deg[1])
        # print(ans2)
        # 打印出函数
        f1 = np.poly1d(ans1)
        f2 = np.poly1d(ans2)
        # 打印出对应的公式
        print(f1)
        print(f2)
        ff1=f1(np.array(temp))
        ff2=f2(np.array(temp))
        # 得到原始数据绘制的图像
        plt.plot(temp, dens,label='data')
        # 得到f1函数对应得系数绘制图像
        plt.plot(temp, ff1,label='degree 1')
        # 得到f2函数对应得系数绘制图像
        plt.plot(temp, ff2,label='degree 2')
        plt.legend()
        plt.show()
        ##********** End **********#
        plt.savefig("step4/stu_img/student.png")

5.第5关:用多项式拟合实验数据并绘图

import numpy as np
import matplotlib.pyplot as plt
class Solution:
    def solve(self, file):
        """
        :type file: str
        :rtype: None
        """
        #请在此按照“编程要求”填写代码
        #********** Begin *********#
        data = np.loadtxt(file,dtype=float,skiprows=1)
        x = data[:,0]
        y = data[:,1]
        p1 = np.polyfit(x,y,1)
        p2 = np.polyfit(x,y,2)
        p3 = np.polyfit(x,y,3)
        ans1 = np.poly1d(p1)
        ans2 = np.poly1d(p2)
        ans3 = np.poly1d(p3)
        x1 = ans1(np.array(x))
        x2 = ans2(np.array(x))
        x3 = ans3(np.array(x))
        plt.plot(x,y,'ro')
        plt.plot(x,y,label = "data")
        plt.plot(x,x1,label = "degree 1")
        plt.plot(x,x2,label = "degree 2")
        plt.plot(x,x3,label = "degree 3")
        plt.legend()
        plt.show()

        ##********** End **********#
        plt.savefig("step5/stu_img/student.png")

十、Python入门之模块

十一、Python入门之函数调用

十二、Python入门之函数结构

十三、Python入门之玩转列表

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

村头卖假发的小郑

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值