考试须知¶

1.填写自己的学号姓名班级等信息,包括文件名以及下面的考生信息。¶

2.将考试文件代码填写完整,如果提示警告,可以忽略。¶

3.最终保存成html格式文件交回。点击左上角file选项,选择download as,再选择HTML,将文件保存成html格式文件。¶

4.考生信息不完整,最终提交文件不是html格式文件等格式问题将酌情扣分。¶

考生信息¶

  • 姓名:李宏超
  • 学号:20407212
  • 班级:计科2002班

1.编写程序,求$1!+2!+3!+...20!$的和¶

In [1]:
# your code
s = 0
def mul(n):
   if n==1:
      return 1
   return n*mul(n-1)

for n in  range(1,21):
   a = mul(n)
   s += a
print(s)
2561327494111820313

2.编写程序,求列表s=[9,7,8,3,2,1,55,6]中元素的个数、最大数和最小数。并在列表s中添加一个元素10,从列表s中删除一个元素55。¶

In [2]:
# your code
list1 =[9,7,8,3,2,1,55,6]
x=len(list1)
y=min(list1)
z= max(list1)
print("列表元素个数:",x,"最小数:",y,"最大数:",z)
list1.append(10)
print(list1)
list1.remove(55)
print(list1)
列表元素个数: 8 最小数: 1 最大数: 55
[9, 7, 8, 3, 2, 1, 55, 6, 10]
[9, 7, 8, 3, 2, 1, 6, 10]

3.编写程序,用循环打印如下图形,不用循环0分¶

TTTTTx
TTTTxx
TTTxxx
TTxxxx
Txxxxx
In [3]:
# your code
for i in range(1,6):
    for j in range(6-i):
        print("T",end="")
    for j in range(i):
        print("x",end="")
    print()
TTTTTx
TTTTxx
TTTxxx
TTxxxx
Txxxxx

4.编写程序,设计一个计算器,用户输入数字选择功能(1-4),其中功能1为加法,2为减法,3为乘法,4为除法,用函数定义加减乘除,然后用户输入两个数字,最终计算出两个数字的相应的加减乘除结果。¶

In [ ]:
# your code
def hello():
    print('欢迎使用本计算器!!!')
    while True:
        select = int(input('请输入要操作的选项:1 加法 2 减法 3 乘法 4 除法'))
        if select == 1:
            add()
        elif select == 2:
            red()
        elif select == 3:
            rid()
        elif select == 4:
            exc()
        else:
            print('你的输入有误,请重新输入!!!')
            continue
        choice = input('是否继续?继续输入Y,输入任意键退出。')
        if choice != 'Y':
            break


def add():
    a = float(input('请输入第一个数:'))
    b = float(input('请输入第二个数:'))
    result = a + b
    print('两个数的和为{}'.format(result))


def red():
    a = float(input('请输入被减数:'))
    b = float(input('请输入减数:'))
    result = a - b
    print('两个数的差为{}'.format(result))


def rid():
    a = float(input('请输入第一个数:'))
    b = float(input('请输入第二个数:'))
    result = a * b
    print('两个数的积为{}'.format(result))


def exc():
    a = float(input('请输入被除数数:'))
    b = float(input('请输入除数:'))
    result = a / b
    print('两个数的商为{}'.format(result))


hello()
欢迎使用本计算器!!!
请输入要操作的选项:1 加法 2 减法 3 乘法 4 除法1
请输入第一个数:1
请输入第二个数:1
两个数的和为2.0
是否继续?继续输入Y,输入任意键退出。Y
请输入要操作的选项:1 加法 2 减法 3 乘法 4 除法2
请输入被减数:2
请输入减数:1
两个数的差为1.0
是否继续?继续输入Y,输入任意键退出。Y
请输入要操作的选项:1 加法 2 减法 3 乘法 4 除法3
请输入第一个数:2
请输入第二个数:2
两个数的积为4.0
是否继续?继续输入Y,输入任意键退出。Y
请输入要操作的选项:1 加法 2 减法 3 乘法 4 除法4
请输入被除数数:4
请输入除数:2
两个数的商为2.0

5.编写程序,定义一个学生类,类属性包括姓名(name)、年龄(age)和成绩(course)[语文、数学、英语],每科成绩的类型为整数。在类方法中,使用get_name函数获取学生的姓名,返回str类型;使用get_age函数获取学生的年龄,返回int类型;使用get_course函数返回3门科目中最高分数,返回int类型。写好类后,用st=Student('zhangming',20,[69,88,100])测试,并输出结果。¶

In [1]:
# your code
class Student:
    def __init__(self,name,age,*cou):
        self.name=name
        self.age=age
        self.course=cou
    def get_name(self):
        return str(self.name)
    def get_age(self):
        return int(self.age)
    def get_course(self):
        return int(max(max(self.course)))
zm=Student('zhangming',20,[69,88,100])
print('学生姓名为:',zm.get_name(),'年龄为:',zm.get_age(),'最高分成绩为:',zm.get_course())
学生姓名为: zhangming 年龄为: 20 最高分成绩为: 100

6.编写程序,根据下表的数据绘制柱状图(条形图)¶

X Y X Y
-3.00 4 0.15 255
-2.50 12 0.75 170
-1.75 50 1.25 100
-1.15 120 1.85 20
-0.50 205 2.45 14
In [5]:
# your code
import pandas as pd
import matplotlib. pyplot as plt
x = ('-3.00','-2.50','-1,75','-1.15','-0.50','0.15','0.75','1.25','1.85','2.45')
y = [4,12,50,120,205,255,170,100,20,14]

plt.bar(x, y)
plt.title(' ')

plt.show()

7.编写程序,某种水泥在凝固时放出的热量Y(cag/g)与水泥中4种化学成分X1、X2、X3、X4有关,现测得13组数据,希望从中选出主要的变量,建立Y与它们的线性回归方程(分别使用线性回归、岭回归、lasso回归)。¶

注:训练集:测试集=8:2,随机种子采用你学号后两位,例如你学号后两位=01,则random_state=1,如果最后两位=34,则random_state=34。最终结果打印出各个回归的w和b系数即可。

序号 X1 X2 X3 X4 Y
1 7 26 6 60 78.5
2 1 29 15 52 74.3
3 11 56 8 20 104.3
4 11 31 8 47 87.6
5 7 52 6 33 95.9
6 11 55 9 22 109.2
7 3 71 17 6 102.7
8 1 31 22 44 72.5
9 2 54 18 22 93.1
10 21 47 4 26 115.9
11 1 40 23 34 83.8
12 11 66 9 12 113.3
13 10 68 8 12 109.4
In [1]:
# your code
from sklearn import model_selection, linear_model
import numpy as np
from sklearn import datasets
boston = datasets.load_boston()
data = np.array(
    [
        [7, 26, 6, 60],
        [1.,  29.,  15.,  52.],
        [11,   56,    8,   20],
        [11,   31,    8,   47],
        [ 7,   52,    6,   33],
        [11,   55,    9,   22],
        [ 3,   71,   17,    6],
        [1,   31,   22,   44],
        [2,   54,   18,   22],
        [21,   47,    4,   26],
        [1,   40,   23,   34],
        [11,   66,    9,   12],
        [10,   68,    8,   12]
    ]
)
target = np.array(
    [
        [78.5],
        [74.3],
        [104.3],
        [87.6],
        [95.9],
        [109.2],
        [102.7],
        [72.5],
        [93.1],
        [115.9],
        [83.8],
        [113.3],
        [109.4]
    ]
)
x_train, x_test, y_train, y_test = model_selection.train_test_split(
    data, target, test_size=0.2, random_state=12
)
lr = linear_model.LinearRegression()
rr = linear_model.Ridge()
la = linear_model.Lasso()
models = [lr, rr, la]
names = ['Linear', 'Ridge', 'Lasso']
for model, name in zip(models, names):
    model.fit(x_train, y_train)
print('线性回归系数w: %s,线性回归截距b: %.2f' %(lr.coef_, lr.intercept_))
print('岭回归系数w: %s,岭回归截距b: %.2f' %(rr.coef_, rr.intercept_))
print('Lasso回归系数w: %s,岭回归截距b: %.2f' %(la.coef_, la.intercept_))
D:\anaconda3\lib\site-packages\sklearn\utils\deprecation.py:87: FutureWarning: Function load_boston is deprecated; `load_boston` is deprecated in 1.0 and will be removed in 1.2.

    The Boston housing prices dataset has an ethical problem. You can refer to
    the documentation of this function for further details.

    The scikit-learn maintainers therefore strongly discourage the use of this
    dataset unless the purpose of the code is to study and educate about
    ethical issues in data science and machine learning.

    In this special case, you can fetch the dataset from the original
    source::

        import pandas as pd
        import numpy as np


        data_url = "http://lib.stat.cmu.edu/datasets/boston"
        raw_df = pd.read_csv(data_url, sep="\s+", skiprows=22, header=None)
        data = np.hstack([raw_df.values[::2, :], raw_df.values[1::2, :2]])
        target = raw_df.values[1::2, 2]

    Alternative datasets include the California housing dataset (i.e.
    :func:`~sklearn.datasets.fetch_california_housing`) and the Ames housing
    dataset. You can load the datasets as follows::

        from sklearn.datasets import fetch_california_housing
        housing = fetch_california_housing()

    for the California housing dataset and::

        from sklearn.datasets import fetch_openml
        housing = fetch_openml(name="house_prices", as_frame=True)

    for the Ames housing dataset.
    
  warnings.warn(msg, category=FutureWarning)
线性回归系数w: [[ 0.8109537   0.22245841 -0.51514435 -0.44689656]],线性回归截距b: 96.99
岭回归系数w: [[ 0.79281528  0.21647633 -0.52727665 -0.45337572]],岭回归截距b: 97.74
Lasso回归系数w: [ 0.74170335  0.23268067 -0.52081238 -0.43832865],岭回归截距b: 96.75

8.编写程序,用朴素贝叶斯算法进行分类,数据集如下¶

注:训练集:测试集=1:1,随机种子采用你学号后两位,例如你学号后两位=01,则random_state=1,如果最后两位=34,则random_state=34。最终结果输出你预测结果、实际结果以及模型得分三项。

序号 年龄 收入 是否为学生 信誉 购买计算机
1 <=30 高 否 中 否
2 <=30 高 否 优 否
3 31-40 高 否 中 是
4 >40 中 否 中 是
5 >40 低 是 中 是
6 >40 低 是 优 否
7 31-40 低 是 优 是
8 <=30 中 否 中 否
9 <=30 低 是 中 是
10 >40 中 是 中 是
11 <=30 中 是 优 是
12 31-40 中 否 优 是
13 31-40 高 是 中 是
14 >40 中 否 优 否
In [2]:
# your code
import numpy as np
import pandas as pd
from sklearn import metrics
# 导入高斯朴素贝叶斯分类器
from sklearn.naive_bayes import GaussianNB
from sklearn.model_selection import train_test_split

x = np.array(
    [
        [1, 3, 0, 1, 0],
        [1, 3, 0, 2, 1],
        [2, 3, 0, 2, 1],
        [3, 2, 0, 1, 1],
        [3, 1, 1, 1, 1],
        [3, 1, 1, 2, 0],
        [2, 1, 1, 2, 1],
        [1, 2, 0, 1, 0],
        [1, 1, 1, 1, 1],
        [3, 2, 1, 1, 1],
        [1, 2, 1, 2, 1],
        [2, 2, 0, 2, 1],
        [2, 3, 1, 1, 1],
        [3, 2, 0, 2, 0],
    ]
)

y = np.array(
    [
        0,1,1,1,1,0,1,0,1,1,1,1,1,0
    ]
)
X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.5, random_state=12)
# 使用高斯朴素贝叶斯进行计算
clf = GaussianNB()
clf.fit(X_train, y_train)
# 评估
y_predict = clf.predict(X_test)
score_gnb = metrics.accuracy_score(y_predict,y_test)

print('该用户是否购买计算机:',y_predict)
print(y_test)
print(score_gnb)
该用户是否购买计算机: [1 1 1 1 1 1 1]
[0 1 1 0 1 0 1]
0.5714285714285714
In [ ]:
 
In [ ]:
 
In [ ]: