# Digital Learning Technology ###### tags: `homework` ## 目錄 [TOC] ## Week 2 ### 2-1 ```typescript a=500 b=30.5 print(a*b) print(a*b,"yuan") print(500,"US dollars is",a*b,"yuan Taiwan dollars") print(500,"US dollars = ",a*b,"yuan Taiwan dollar",sep='') ``` > 15250.0 15250.0 yuan 500 US dollars is 15250.0 yuan Taiwan dollars 500US dollars = 15250.0yuan Taiwan dollar ### 2-2 ```typescript ch=int(input()) en=int(input()) ma=int(input()) pr=int(input()) print(ch+en+ma+pr) print((ch+en+ma+pr)/4) ``` > 80 80 90 90 340 85.0 ### 2-3 ```typescript alpha='ABCDEFGHIJKLMNOPQRSTUVWXYZ' idnum=[] idnum=input() #print(idnum[0]) for i in range(len(alpha)): if(idnum[0]==alpha[i]): j=i if j<10: j='0'+str(j+1) else: j=j+1 print(j,f"{idnum[1:]}",sep='') ``` > A1545645 011545645 ## Week 3 ### 3-1 ```typescript ch=int(input()) en=int(input()) ma=int(input()) pr=int(input()) avg=(ch+en+ma+pr)/4 print(avg) if avg>=80: print('A') print('pass') if avg>=70 and avg<=79: print('B') print('pass') if avg>=60 and avg<=69: print('C') print('pass') if avg<=60: print('D') print('not pass') ``` > 80 80 90 90 85.0 A pass ### 3-2 ```typescript n=1 total_list=[] while(n!=0): n=int(input()) total=-1 for i in range(int(n)+1): powi=pow(i,i) total=total+powi if total>=10: total=total%10 else: total=total total_list.append(total) for j in range(len(total_list)-1): print(total_list[j]) ``` > 1 2 3 4 5 0 1 5 2 8 3 ### 3-3 ```typescript n=1 count_list=[] try: #程式嘗試去執行這段程式碼,如果出錯了,則執行某段程式碼 while(n!=0): n=int(input()) s=[] for i in range(n): s.append(input()) count=0 for i in range(len(s)-1): for j in range(len(s)-1): if s[j]>s[j+1]: s[j],s[j+1]=s[j+1],s[j] count=count+1 count_list.append(count) except EOFError: pass for i in range(len(count_list)-1): print(count_list[i]) ``` > 3 3 2 1 0 3 ## Week 4 ### 4-1 ```typescript import pandas as pd n = int(input()) s=[] s1 = [] for i in range(n): s=[int(a) for a in input().split(" ")] total = s[1]+s[2]+s[3] s.append(total) avg = round(total/3,1) s.append(avg) if (avg>=60): s.append("Pass") else: s.append("Not pass") s1.append(s) df = pd.DataFrame(s1, columns=['Number', 'Chinese', 'English', 'Math', 'Total', 'Average', 'Achievement']) df.to_html("hw.html") ``` > ![](https://i.imgur.com/MhiP2vS.jpg) ### 4-2 ```typescript import numpy as np ar=[] a,b=map(int,input().split()) for i in range (a): num =[int(x) for x in input().split()] ar.append(num) array=np.array(ar) while(True): num=int(input("request:")) if(num==1): a,b=map(int,input().split()) array = array.ravel() array =np.reshape(array,(a,b)) elif(num==4): print(array) elif(num==2): ar=[] a,b=map(int,input().split()) for i in range (a): num =[int(x) for x in input().split()] ar.append(num) array2=np.array(ar) if(array.shape[1]==array2.shape[0]): array = array.dot(array2) else: print("fail") elif(num==3): array=array.T elif(num==5): break ``` >2 3 1 2 3 1 1 1 request:1 3 2 request:4 [[1 2] [3 1] [1 1]] request:2 2 3 1 1 1 1 1 1 request:4 [[3 3 3] [4 4 4] [2 2 2]] request:2 2 3 2 2 2 2 2 2 fail request:3 request:4 [[3 4 2] [3 4 2] [3 4 2]] request:5 ## Week 6 ### 6-1 ```typescript <html> <head> <title>introduce myself</title> <style> body { background-image: url("https://www.dramaqueen.com.tw/images/video_poster/2020/202001221113423206055f70736a9ca6616e85e37aa7df6fa7.jpg"); background-repeat:no-repeat; background-attachment:fixed; background-position:center; } </style> </head> <body style="background-color:powderblue;"> <h1>Hi</h1> <h3>Name : 康書語</h3> <h3>Hobby : <a href="https://www.facebook.com/">Click!</a> </h3> <h3>Admire:<a href="https://www.youtube.com/">Click!</a> </h3> <img src="https://www.ingredients-store.com/data/images/c1/204x208.shrink_only.q85/fine-logo.png?_images_storage"> </br> </br> <img src="https://media-exp1.licdn.com/dms/image/C560BAQEL5HagAaFaoA/company-logo_200_200/0?e=2159024400&v=beta&t=1X-JLK8QYsAQB4VoMxhPAMFSem8GX70r0AVadocDXfo"> </body> </html> ``` > ![]()![](https://i.imgur.com/zkIp1Wd.png) ## Week 7 ```typescript= import requests from bs4 import BeautifulSoup with requests.Session() as s: page = s.get('http://sys.ndhu.edu.tw/AA/CLASS/subjselect/Default.aspx') soup = BeautifulSoup(page.content, 'lxml') payload_loginPage = { 'ctl00$ContentPlaceHolder1$ed_StudNo': 'XXXXXX', 'ctl00$ContentPlaceHolder1$ed_pass': 'XXXXXX', 'ctl00$ContentPlaceHolder1$BtnLogin': '登入' } payload_loginPage["__VIEWSTATE"] = soup.select_one("#__VIEWSTATE")["value"] payload_loginPage["__VIEWSTATEGENERATOR"] = soup.select_one("#__VIEWSTATEGENERATOR")["value"] payload_loginPage["__EVENTVALIDATION"] = soup.select_one("#__EVENTVALIDATION")["value"] s.post('http://sys.ndhu.edu.tw/AA/CLASS/subjselect/Default.aspx', data=payload_loginPage) page = s.get('http://sys.ndhu.edu.tw/AA/CLASS/subjselect/course_history.aspx') soup = BeautifulSoup(page.content, 'lxml') data = {'ctl00$ContentPlaceHolder1$Button3':'查詢選課操作記錄'} data["__VIEWSTATE"] = soup.select_one("#__VIEWSTATE")["value"] data["__VIEWSTATEGENERATOR"] = soup.select_one("#__VIEWSTATEGENERATOR")["value"] data["__EVENTVALIDATION"] = soup.select_one("#__EVENTVALIDATION")["value"] page = s.post('http://sys.ndhu.edu.tw/AA/CLASS/subjselect/course_history.aspx', data = data) print(page.text) ``` ## Week 10 ### 10-1 & 10-2 ```typescript= import pandas as pd import matplotlib.pyplot as plt df=pd.read_csv('CommodityPrice.csv') for i in range(len(df)): df.Date[i] = df.Date[i].split('/', 1)[1] if i < 20: df['Change%'][i] = float(df['Change%'][i].split('%')[0]) else: df['Change%'][i] = float(df['Change%'][i].split('%')[0]) data = df[df.Price>1000] print(data) gold = data[data['Commodity']=='Gold'] palladiun = data[data['Commodity']=='Palladiun'] gold_futr = data[data['Commodity']=='Gold Futr'] cocoa_future = data[data['Commodity']=='Cocoa Future'] data2 = df[(df.Price>=500) & (df.Price<1000)] print(data2) platinum = data2[data2['Commodity']=='Platinum'] wheat_future = data2[data2['Commodity']=='Wheat Future'] soybean_futr = data2[data2['Commodity']=='Soybean Futr'] date_list = gold.Date.tolist() fig = plt.figure(figsize=(15,12)) #plt.subplot(2, 1, 1) ax1 = fig.add_subplot(2,1,1) ax1.plot(date_list, gold.Price, label="Gold") ax1.plot(date_list, palladiun.Price, label="Palladiun") ax1.plot(date_list, gold_futr.Price, label="Gold_Futr") ax1.plot(date_list, cocoa_future.Price, label="Cocoa_Future") ax1.axis(ymin=1000,ymax=3000) ax1.set_title("Commodity Price(>= 1000)") ax1.set_xlabel("Date") ax1.set_ylabel("Price") ax1.legend() ax2 = fig.add_subplot(2,1,2) ax2.plot(date_list, gold['Change%'], 'c*--', label="Gold") ax2.plot(date_list, palladiun['Change%'], 'y*--', label="Palladiun") ax2.plot(date_list, gold_futr['Change%'], 'g*--', label="Gold_Futr") ax2.plot(date_list, cocoa_future['Change%'] ,'r*--', label="Cocoa_Future") ax2.axis(ymin=-15,ymax=15) ax2.set_title("Commodity Change%(Price >= 1000)") ax2.set_xlabel("Date") ax2.set_ylabel("Chamge%") ax2.grid() ax2.legend() fig.savefig('1.jpg') fig = plt.figure(figsize=(15,12)) #plt.subplot(2, 1, 1) ax1 = fig.add_subplot(2,1,1) ax1.plot(date_list, platinum.Price, label="Palladiun") ax1.plot(date_list, wheat_future.Price, label="wheat_future") ax1.plot(date_list, soybean_futr.Price, label="soybean_futr") #ax1.plot(date_list, cocoa_future.Price, label="Cocoa_Future") ax1.axis(ymin=500,ymax=1000) ax1.set_title("Commodity Price(>= 500 and <1000)") ax1.set_xlabel("Date") ax1.set_ylabel("Price") ax1.legend() ax2 = fig.add_subplot(2,1,2) ax2.plot(date_list, platinum['Change%'], 'c*--', label="Palladiun") ax2.plot(date_list, wheat_future['Change%'], 'y*--', label="wheat_future") ax2.plot(date_list, soybean_futr['Change%'], 'g*--', label="soybean_futr") #ax2.plot(date_list, cocoa_future['Change%'] ,'r*--', label="Cocoa_Future") ax2.axis(ymin=-4,ymax=4) ax2.set_title("Commodity Change%(Price >= 500 and < 1000)") ax2.set_xlabel("Date") ax2.set_ylabel("Chamge%") ax2.grid() ax2.legend() fig.savefig('2.jpg') ``` 1.![](https://i.imgur.com/l4yzBGU.jpg) 2.![](https://i.imgur.com/Bamg9H7.jpg) ## Week 11 我在亂做 ```typescript= import pandas as pd import numpy as np import matplotlib.pyplot as plt df = pd.read_csv("hualian.csv") train = df[0:10] x = train[['年度']] y = train[['總人口數']] n = len(x) x_mean = x.mean() y_mean = y.mean() x = np.array(x) y = np.array(y) diff = (x-x_mean)*(y-y_mean) covar = diff.sum()/10 print("共變異數:", covar) b= covar/(x.std()** 2) print("斜率(迴歸係數):", b) intercept = y_mean - b * x_mean print("截距 intercept:", intercept) print("迴歸線:Y= {}X + {}".format(b, intercept) ) x1 = np.array([96]) y_predict = b * x1 + intercept print('\n[96的y_predict:', y_predict) x_new = np.linspace(x.min(), x.max(), 100) y_new = b * x_new + intercept plt.plot(x, y, 'go',x_new, y_new) plt.plot(x1, y_predict, 'ro') plt.show() err = (y_predict-343302)/100 err ``` ![](https://i.imgur.com/qKKRIDY.png) ## Week 12 ```typescript= import pandas as pd import numpy as np from sklearn import datasets from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt boston = datasets.load_boston() print("keys:\n", boston.keys()) print("\ndata shape:\n", boston.data.shape) print("\nfield name in data:\n", boston.feature_names) print("\nDescription:", boston.DESCR) X = pd.DataFrame(boston.data, columns=boston.feature_names) print(X.head()) target = pd.DataFrame(boston.target, columns=["MEDV"]) print('\n','target:', '\n', target.head(), sep='\n') y = target["MEDV"] lm = LinearRegression() lm.fit(X, y) print("迴歸係數:", lm.coef_) print("截距:", lm.intercept_ ) coef = pd.DataFrame(boston.feature_names, columns=["features"]) coef["estimatedCoefficients"] = lm.coef_ print("\n迴歸係數:", coef, sep = '\n') plt.scatter(X.RM, y) plt.xlabel("Average numbwer of rooms per dwelling(RM)") plt.ylabel("Housing Price(MEDV)") plt.title("Relationship between RM and Price") plt.show() X = pd.DataFrame(boston.data, columns=boston.feature_names) target = pd.DataFrame(boston.target, columns=["MEDV"]) y = target["MEDV"] lm = LinearRegression() lm.fit(X, y) predicted_price = lm.predict(X) print(predicted_price[0:5]) plt.scatter(y, predicted_price) plt.xlabel("Price") plt.ylabel("Predicted Price") plt.title("Price vs Predicted Price") plt.show() XTrain, XTest, yTrain, yTest = train_test_split(X, y, test_size=0.33, random_state=5) lm = LinearRegression() lm.fit(XTrain, yTrain) pred_train = lm.predict(XTrain) pred_test = lm.predict(XTest) MSE_train = np.mean((yTrain-pred_train)**2) MSE_test = np.mean((yTest-pred_test)**2) print("訓練資料的MSE:", MSE_train) print("測試資料的MSE:", MSE_test) print("訓練資料的R-squared:", lm.score(XTrain, yTrain)) print("測試資料的R-squared:", lm.score(XTest, yTest)) plt.scatter(yTest, pred_test) plt.xlabel("Price") plt.ylabel("Predicted Price") plt.title("Price vs Predicted Price") plt.show() predicted_price = lm.predict(X) print(predicted_price[0:5]) MSE = np.mean((y-predicted_price)**2) print("MSE:", MSE) print("R-squared:", lm.score(X, y)) lm = LinearRegression() lm.fit(XTrain, yTrain) pred_train = lm.predict(XTrain) pred_test = lm.predict(XTest) plt.scatter(pred_train, pred_train-yTrain, c="b", s=40, alpha=0.5, label="Training Data") plt.scatter(pred_test, pred_test-yTest, c="r", s=40, label="Test Data") plt.hlines(y=0, xmin=0, xmax=50) plt.title("Residual Plot") plt.ylabel("Residual Value") plt.legend() plt.show() ``` Relationship between RM and Price ![](https://i.imgur.com/Xs8WYrE.png) Price vs Predicted Price ![](https://i.imgur.com/WaWTRGH.png) ![](https://i.imgur.com/GoRmdjR.png) Residual Plot ![](https://i.imgur.com/wO7ZgXg.png) ## Week 13 ### 13 ```typescript= import pandas as pd import numpy as np from sklearn import preprocessing, tree from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt adult = pd.read_csv("adult.csv") adulttest = pd.read_csv("adulttest.csv") label_encoder = preprocessing.LabelEncoder() money = label_encoder.fit_transform(adult["annual-income"]) sex = label_encoder.fit_transform(adult["sex"]) sex_test = label_encoder.fit_transform(adulttest["sex"]) money_test = label_encoder.fit_transform(adulttest["annual-income"]) X = pd.DataFrame(sex) X.columns = ["sex"] y = pd.DataFrame(money) y.columns = ["annual-income"] Xtest = pd.DataFrame(sex) Xtest.columns = ["sex"] ytest = pd.DataFrame(money) ytest.columns = ["annual-income"] XTrain, yTrain = X, y dtree = tree.DecisionTreeClassifier() dtree.fit(XTrain, yTrain) print("準確率:", dtree.score(Xtest, ytest)) preds = dtree.predict_proba(X=Xtest) print(pd.crosstab(preds[:,0], columns=[Xtest["sex"]])) pd.crosstab(preds[:,0], columns=[Xtest["sex"]]).to_csv("410521232_ID3_predict.txt") from sklearn import preprocessing, tree, neighbors k = 3 knn = neighbors.KNeighborsClassifier(n_neighbors=k) knn.fit(X, y) print("準確率:", knn.score(Xtest, ytest)) print(knn.predict(Xtest)) print(ytest.values) preds = knn.predict(Xtest) print(pd.crosstab(preds[:], columns=[Xtest["sex"]])) pd.crosstab(preds[:], columns=[Xtest["sex"]]).to_csv("410521232_KNN_predict.txt") ```