明天 今天上机考试,说实话有点慌张(两小时六道题,写得完写不完心里还没点数
冲呀
话说回来今日昨天的 运势(再熬夜我是猪头系列/我必洗澡 T x T
现在开始代码阶段复习,(因为ldw老师说他考六道题,我也不知道大致分布,所以只能盲猜。有一说一,课后作业有13个,二选一我还达不到六分之一吗,别紧张……好紧张哈哈哈哈哈哈哈哈哈哈哈哈哈哈,大笑掩饰,欲盖弥彰哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈)
回顾一下作业好了
- 三角形形状判断(反正我是会的
基本的input操作& if判断 &print操作
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/10/22 10:37
# @Author : Chen Shan
# Function :Judge triangle type
a = int(input("请输入一个整数(三角形的边长a):"))
……
if ……:
print("这三条边无法构成一个三角形")
elif ……:
print("这是一个等腰三角形")
else:
print("这是一个三角形")
- 一张纸折叠多少次才可以到达珠穆朗玛峰的高度(这题果然很ldw老师,众所周知的是一张纸最多可以折叠7次orz
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/10/22 10:37
# @Author : Chen Shan
# Function : Calculate the number of times the paper is folded in half
paper_width = 0.00008
mountain_width = 8848.13
cnt = 0
while True:
……
if ……:
break
print("需要对折"+str(cnt)+"次才可以")
- 求解鸡兔同笼问题(没得问题我也会‘
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/10/22 10:37
# @Author : Chen Shan
# Function : Solve the problem of chicken and rabbit in the same cage
a = int(input("请输入一个整数(头的个数):"))
b = int(input("请输入一个整数(腿的个数):"))
hand = 0
foot = 0
for i in range(0,a+1):
if &:
print("鸡的个数是:"+……+",兔的个数是"+……)
break
else:
print("此输入无解")
- 读写多维矩阵(主要考的知识点就是读写操作吧…其实我有点忘记了毕竟我俩小时才写出一个代码我凑了
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/10/22 10:37
# @Author : Chen Shan
# Function : Read & write multidimensional matrix
# file_name:读入或写入的文件名称
# data_list:读入或写入的数据链表
# data_tpye:数据类型
# 1:int;2:float;3:string
# n:矩阵维度
def f_write(file_name,data_list,n=2,data_type=1):
f = open(file_name,'w')
if n != 2:
……
elif n == 2:
……
f.close()
def f_read(file_name,output_list=[],n=2,data_type=1):
f = open(file_name,'r')
if n != 2:
……
elif n == 2:
……
f.close()
print(output_list)
# =========== test on n=3 int =============
int_3_list=[[[1,2,2,3],[2,3,3,4]],[[1,2,2,3],[2,3,3,4]],[[1,2,2,3],[2,3,3,4]]]
f_write('int_3_test.txt',int_3_list,n=3)
int_o_3_list=[]
f_read('int_3_test.txt',int_o_3_list,n=3)
print('------------------------')
# --- test on n=3 string ---
str_3_list = [[['a','b','c'],['d','ef','g']],[['a','b','c'],['d','ef','g']]]
str_o_3_list=[]
f_write('str_3_test.txt',str_3_list,n=3,data_type=3)
f_read('str_3_test.txt',str_o_3_list,n=3,data_type=3)
# print(str_3_list)
print('------------------------')
# --- test on n=3 float ---
float_3_list = [[[1.11,2.22,3.33],[1.34,2.45,3.56]],[[1.11,2.22,3.33],[1.34,2.45,3.56]]]
float_o_3_list=[]
f_write('float_3_test.txt',float_3_list,n=4,data_type=2)
f_read('float_3_test.txt',float_o_3_list,n=4,data_type=2)
# print(float_3_list)
# # =========== test on int data_type =============
# int_list = [[1,2,2,3],[2,3,3,4]]
# int_o_list=[]
# f_write('int_test.txt',int_list)
# f_read('int_test.txt',int_o_list)
#
# # ========= test on float data_type =============
# float_list = [[1.11,2.22,3.33],[1.34,2.45,3.56]]
# float_o_list=[]
# f_write('float_test.txt',float_list,data_type=2)
# f_read('float_test.txt',float_o_list,data_type=2)
#
# # ========= test on string data_type ============
# str_list = [['a','b','c'],['d','ef','g']]
# str_o_list=[]
# f_write('str_test.txt',str_list,data_type=3)
# f_read('str_test.txt',str_o_list,data_type=3)
- 自定义数据类型staff(职员)&方法&捕获异常&处理异常
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/10/15 10:40
# @Author : ChenShan
# Function : Define the staff class, create a new staff object & detect the exception of user input type
class staff:
def __init__(self,id_val,name_val,age_val,salary_val):
self.id = id_val
self.name = name_val
self.age = age_val
self.salary = salary_val
def __str__(self):
print("Name:"+self.name)
print("Id:"+str(self.id))
print("Age:"+str(self.age))
print("Salary:"+str(self.salary))
def Chage_val(self,age_val,salary_val):
……
class rangeError(Exception):
pass
while True:
id_val = input('Input id of this staff :')
try:
……
break
except ValueError:
……
name_val = input('Input name of this staff:')
while True:
age_val = input('Input age of this staff:')
try:
……
if ……:
……
break
except ValueError:
……
except rangeError:
……
while True:
salary_val = ……
try:
……
break
except ValueError:
……
peo = staff(id_val,name_val,age_val,salary_val)
peo.__str__()
peo.Chage_val(35,30000)
peo.__str__()
- 二次函数的拟合(随机生成节点拟合函数)
我记得我当时做题的时候先是写的指数函数拟合(因为二次函数拟合效果太差了,自我怀疑,后来一次偶然的机会我发现其实还行吧哈哈哈然后就交作业了,可怕)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/10/22 10:37
# @Author : Chen Shan
# Function : Randomly generate 50 points, fit binary function and present
import numpy as np
from scipy.optimize import leastsq
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
import random
# 1 ----------二次函数拟合,point (x,y)随机生成
xx = []
yy = []
def A(params, x):
a, b, c = params
return a * x ** 2 + b * x + c
def nosie():
for i in range(0,10):
x = random.uniform(1,10)
……
……
yy.append(y)
……
X = np.array(xx)
Y = np.array(yy)
# 误差函数,即拟合曲线所求的值与实际值的差
def error(params, x, y):
return ……
# 对参数求解
def slovePara():
p0 = [10, 10, 10]
Para = leastsq(error, p0, args=(X, Y))
return Para
Para = ……
a, b, c = Para[0]
# print("a = "+ str(a) + ", b = "+ str(b) + ", c = "+ str(c))
# print("cost:" + str(Para[1]))
print("y = " + str(round(a, 2)) + "x*x+" + str(round(b, 2)) + "x+" + str(c))
plt.figure(figsize=(8, 6))
plt.scatter(X, Y, color="green", label="sample data", linewidth=2)
x = np.linspace(0, 12, 100)
y = a * x * x + b * x + c
plt.plot(x, y, color="red", label="solution line", linewidth=2)
plt.legend()
plt.show()
# # 2----------指数函数拟合,point x 随机生成
……
……
……
# plt.plot(xdata, y2, 'r--')
#
# print("y = "+str(popt[0])+" * np.exp(-"+str(popt[1])+" * x) + "+str(popt[2]))
#
# plt.show()
- 读取csv文件 回答具体问题(这个算是读的比较熟练了吧……比较常见……对于后面出现的xml&m啥啥的文件来说)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/10/29 10:32
# @Author : Chen Shan
# Function : Simple data analysis, read csv file and save it in DataFrame
import os, glob
from pandas import Series,DataFrame
import pandas as pd
csv_file = ……
csv_data = pd.read_csv(csv_file,engine='python')
csv_df = DataFrame(csv_data)
# print(csv_df)
# print('-----')
# print(csv_df['Country'])
# print('-----')
# print(csv_df.shape)
# print(csv_df['Currency units per �1'])
shape = csv_df.shape
usa_cur = 0
china_cur = 0
for i in range (shape[0]):
……
print("Answer 1. exchange rate value of USA is "+str(usa_cur)+" & exchange rate value of China is "+ str(china_cur))
sum_cur = 0
max_cur = 0
max_country = 0
min_cur = 10010
min_country = 0
print("Answer 3. Countries with smaller exchange rates than USA are as follows :")
for i in range (shape[0]):
……
sum_cur = ……
avg_cur = sum_cur / shape[0]
print("Answer 2. " + max_country + "with the largest exchange rate value is " + str(max_cur) )
print(" & " + min_country + " with the lowest exchange rate value is " + str(min_cur))
print(" & the average exchange rate value is " +str(avg_cur))
- 读取xml,提取表格数据(拿到尖括号里的东西,先别慌先把对象输出再取值,可以能行最棒???
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/11/5 10:53
# @Author : Chen Shan
# Function :Using Python to read data in XML format and store it in data frame format
from lxml import objectify
import xml.etree.cElementTree as et # 读取xml文件的包
import pandas as pd
xml_tree = et.ElementTree(file=……) # 文件路径
dict = {'TITLE':[], 'ARTIST':[], 'COUNTRY':[],'COMPANY':[],'PRICE':[],'YEAR':[]}
root = xml_tree.getroot()
for sub_node in root:
for node in sub_node:
# print(node, node.tag, node.attrib, node.text)
……
data_frame = ……
print(data_frame)
- 爬学院网教师信息,数据用dataframe存储(这里用的是最蠢的方法if筛选)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/11/5 11:15
# @Author : Chen Shan
# Function :Using Python to crawl useful data in HTML format and store it in dataframe data format
from lxml.html import parse
from urllib.request import urlopen
import pandas as pd
parsed = parse(urlopen('http://info.zufe.edu.cn/xygk/szdw.htm'))
doc = parsed.getroot()
strongs = doc.findall('.//strong')
links = doc.findall('.//a')
tds = doc.findall('.//td')
j.text_content())
for item in tds:
……
flag = 0
index = 1
dict = {'FULL_NAME':[], 'POSITION':[], 'HOME_LINK':[]}
for item in tds:
for j in links:
if ……:
if ……:
flag=1
break
if ……:
if ……:
position = 'Professor'
elif ……:
position = 'Associate professor'
else:
position = 'Lecturer'
index+=1
dict['FULL_NAME'].append(……)
dict['HOME_LINK'].append(……)
dict['POSITION'].append(……)
break
if flag == 1:
break
data_frame = pd.DataFrame(dict)
print(data_frame)
- 读取mat三维数据,绘图分析
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/11/12 11:05
# @Author : Chen Shan
# Function : Read mat 3D data & plot analysis
import scipy.io as sio
import math
import matplotlib.pyplot as plt
raw_K=sio.loadmat(……)
raw_V=sio.loadmat(……)
k = raw_K['Subject1K']
v = raw_V['Subject1V']
subkk = []
subvv = []
index = 0
flag = 0
minnum = 10
maxnum = 30
for ik in k:
# print(ik)
for iik in ik:
# print(iik)
if ……:
if ……:
……
elif ……:
flag = 1
break
index = index + 1
if flag == 1:
break
# print(subkk)
# print(index)
index = 0
for iv in v:
# print(iv)
for iiv in iv:
# print(iiv)
……
if flag == 1:
break
junk = []
sk1 = []
sk2 = []
index = 0
for ik in k:
for iik in ik:
if ……:
if ……:
tempk = (iik[0]+iik[1]+iik[2]+iik[3])/4
temps = ……
temps = math.sqrt(temps)
junk.append(tempk)
sk1.append(tempk+temps)
sk2.append(tempk-temps)
elif ……:
flag = 1
break
index = index + 1
if flag == 1:
break
# print(junk)
fig = plt.figure()
ax1 = fig.add_subplot(2,1,1)
ax1.plot(subkk,'go--',label = 'Subject1K')
ax1.plot(subvv,'bo--',label = 'Subject1V')
ax1.legend(loc='best')
ax2 = fig.add_subplot(2,1,2)
……
plt.show()
# print(k)
# print(v)
- 设计GUI界面选择年份和本金信息之后呈现本息金额结果
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/11/26 10:40
# @Author : ChenShan
# Function : Using PyQt5 interface to calculate compound interest
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class Form(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.principal = QLabel("Principal :")
self.pDoubleBox = QDoubleSpinBox()
self.pDoubleBox.setRange(1000.00, 1000000.00)
self.pDoubleBox.setValue(10000.00)
self.pDoubleBox.setPrefix("$ ")
self.rate = QLabel("Rate :")
self.rDoubleBox = QDoubleSpinBox()
self.rDoubleBox.setRange(0.00, 60.00)
self.rDoubleBox.setValue(5.00)
self.rDoubleBox.setSuffix(" %")
self.year = QLabel("Years :")
self.timeComboBox = QComboBox()
self.timeComboBox.addItems(["1 year", "2 years", "5 years", "10 years", "20 years"])
self.amount = QLabel("Amount :")
self.res = QLabel("$ 10050")
grid = QGridLayout()
grid.addWidget(self.principal, 0, 0)
grid.addWidget(self.pDoubleBox, 0, 1)
grid.addWidget(self.rate, 1, 0)
grid.addWidget(self.rDoubleBox, 1, 1)
grid.addWidget(self.year, 2, 0)
grid.addWidget(self.timeComboBox, 2, 1)
grid.addWidget(self.amount, 3, 0)
grid.addWidget(self.res, 3, 1)
self.setLayout(grid)
self.pDoubleBox.valueChanged.connect(self.updateUi)
self.rDoubleBox.valueChanged.connect(self.updateUi)
self.timeComboBox.currentIndexChanged.connect(self.updateUi)
self.setWindowTitle("HOMEWORK-11 Interest")
def updateUi(self):
p = ……
r = ……
y = ……
# print(p)
# print(r)
# print(y)
if y == "1 year":
……
……
for i in range(0,y):
……
self.res.setText("$ {0:.2f}".format(ans))
app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()
- GUI编程-有点像画板工具
- GUI编程-打地鼠小游戏