1. 课后练习-机器学习简介和Python的基本操作

本文最后更新于 2024年1月27日 下午

课后练习1

Solve the questions below by writing a Python function or script.

Q1. Add up the numbers from 100 to 200 and output their sum, using while and for loops.

for loop:

1
2
3
4
total = 0
for i in range(100,201): #注意range不包括右边项
total+=i
print("for loop sum:",total)
while loop:
1
2
3
4
5
6
total=0
counter = 100
while counter < 201:
total= total+counter #++不能在python当中使用
counter+=1 #while 循环里面没有自增加
print('for loop sum:',total)
## Q2. Read a string from console and output its length, swap its cases(转换大小写), convert it to lower case and upper case, and reverse it. (Hint: try string slice with step -1)
1
2
3
4
5
6
7
8
9
10
s= input("enter the string:")
print("the length of the string:",len(s))

swap=str.swapcase(s) #str.swapcase() 转换大小写

print("swapcase is :",swap)
print("lowercase:",str.lower(s)) #str.lower/upper()
print("uppercase:",str.upper(s))

print("reverse order:",s[::-1]) #[起点:终点:步长]
## Q3. Read a string from console. Split the string on space delimiter (” ”) and join using a hyphen (”-”). (Example: input the string, ”this-is a string” and output as ”this is-a-string”)
1
2
s="hello world"
print("replace:",str.replace(s,"","-")) #str.replace(string,"","")交换前后元素
## Q4. Learn the Python list operations and follow the commands below: - Initialize an empty list L.
- Add 12, 8, 9 to the list.
- Insert 9 to the head of the list;
- Double the list. (e.g. change L = [1, 2, 3] to L = [1, 2, 3, 1, 2, 3])
- Remove all 8 in the list.
- Reverse the list.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
L=[]
print(L)

L.append(12) #List.append() 列表在末尾添加
L.append(8)
L.append(9)
print(L)

L.insert(0,9) #list.insert(position,element) 在列表的指定位置添加一个元素
L=[9]+L #另一种方式

L=L+L
print(L)
L=L*2 #另一种方法
L=L.extend(L) #list.extend(list) 在列表的末尾添加一个列表
print(L)

number_eights=L.count(8)
for i in range(0,number_eight):
L.remove(8) #list.remove(element) 在列表中移除第一个【element】元素
#另一种解决办法
while 8 in L:
L.remove(8)

L.reverse() #list.reverse() 列表内倒序
print(L)

Q5. Learn Python matrix operations by completing the following tasks:

  • Create a 3x2 matrix named A, with all ones.
  • Create a 3x2 matrix named B, where \(𝐵 =\begin{bmatrix} 1&2\\ 3&4 \\ 5&6 \end{bmatrix}\)
  • Print A and B.
  • Transpose A to be a 2x3 matrix.
  • Multiply matrix A with matrix B and store the output in matrix C.
  • Print the dimensions of C.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    import numpy as np #import packagename 加载库  import packagename as nickname 加载并替换库的名字
    A=np.ones(3,2) #numpy.ones(row,line)
    print(A)

    B=np.array([[1,2],[3,4],[5,6]]) #numpy.array() 创建矩阵,用法同左边
    print(B)

    print(A,B)

    A=A.reshape((2,3)) #numpy.reshape((row,line)) 重新改写矩阵的大小
    A=np.transpose(A) #numpy.transpose(matrix) 返回转置矩阵
    print(A)

    C=A @ B #@ 矩阵叉乘
    print(C.shape) #matrix.shape 矩阵的大小
    # Q6. Use 𝑀 for the following tasks,
    \[𝑀 =\begin{bmatrix}−2&−4&2 \\ −2&1&2 \\ 4&2&5 \end{bmatrix}\]
  • Calculate the eigenvalues and eigenvectors for M. (hint: use numpy.linalg.eig)
  • Use matplotlib to plot the eigenvalues in a graph.
  • Save the eigenvalues into a file named “eig.npy” (hint: use numpy.save).
  • Load the saved file into a new variable called load_eig and print the values.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    import numpy as np
    from matplotlib import plot as plt
    M=[[-1,-4,2],[-2,1,2],[4,2,5]]
    eignval,eignvect=np.linalg,eig(M) #numpy.linalg,eig(Matrix) 返回两个值,第一个是特征值,第二个是特征向量
    print(eignval)

    plt.plot(eignval)

    np.save("eig",eigval) #numpy.save("filename",value) 将值在当前目录下以“filename.npy”储存

    load.eig=np.load("eigval.npy") #numpy.load("path") 返回加载的文件

1. 课后练习-机器学习简介和Python的基本操作
https://l61012345.top/2021/01/23/Machine Learning-NAU/1.a 课后练习/
作者
Oreki Kigiha
发布于
2021年1月23日
更新于
2024年1月27日
许可协议