This commit is contained in:
github 2020-11-16 21:27:38 +08:00
parent 368e204a10
commit 95145eba70
15 changed files with 196 additions and 43 deletions

View File

@ -11,15 +11,15 @@
# def 方法2(self, 参数列表):
# pass
class Cat:
name = ''
name = 'lili'
def __init__(self):
# self.name = 'Tom'
self.name = 'Tom'
print('init')
def __str__(self):
return(self.name)
def drink(self):
print('drink')
cat = Cat()
cat.name = 'Tom'
# cat.name = 'Jack'
print(f'我是小猫{cat},我的id是{id(cat)}',cat,cat.name)
cat.drink()

View File

@ -1,6 +1,6 @@
# 文件重命名
import os
os.rename('test.txt', 'test.py') #重命名
os.rename('test.txt', 'Week5 Monte Carlo Methods.py') #重命名
# 删除文件
import os
@ -8,7 +8,7 @@ os.remove('test.txt') #删除
# 复制文件
import shutil
shutil.copyfile('test.txt', 'test.py')
shutil.copyfile('test.txt', 'Week5 Monte Carlo Methods.py')
# 遍历文件夹下的文件
import os

View File

@ -0,0 +1,7 @@
l = [1,2,3,4,5]
it = iter(l)
print(next(it))
print(next(it))
print(next(it))
print(next(it))

View File

@ -67,3 +67,5 @@ for i,ele in enumerate(a):

View File

@ -2,7 +2,7 @@
x = [[1,2,3], [4,5,6], [7,8,9]]
y = [num for i in x for num in i]
print(y)
print(f"y = [num for i in x for num in i] :{y}")
y = []
for i in x:
for num in i:
@ -14,35 +14,12 @@ x = [-1,-4,6,7.5,-2.3,9,-11]
y = [i for i in x if i>0]
print(y)
x = [(x, y) for x in range(3) for y in range(3)]
print(x)
x = [[x, y] for x in range(3) for y in range(3)]
print("[(x, y) for x in range(3) for y in range(3)]: ",x)
x = [(x, y) for x in [1, 2, 3] for y in [3, 1, 4] if x != y]
print(x)
# 列表综合练习 写一个循环,不断的问用户想买什么,用户选择一个商品编号,
# 就把对应的商品添加到购物车里最终用户输入q退出时打印购物车里的商品列表
l1 = [['a',23],['b',34],['c',33],['d',345]]
l2 = []
print("商品列表****************")
for (index, i) in enumerate(l1):
print("商品{},价格为{}", index, i)
while True:
choise = input("请输入你选择的商品编号:")
if choise.isdigit():
if int(choise) in range(len(l1)) :
print("你选择的是{}".format(choise))
l2.append(l1[int(choise)])
print(l2)
else:
print("你选的商品不在列表中")
elif choise == 'q':
break
if len(l2)>0:
print("你选的商品如下:")
for index,i in enumerate(l2):
print("商品编号{},商品名称{},商品价格{}".format(index,i[0],i[1]))
print("[(x, y) for x in [1, 2, 3] for y in [3, 1, 4] if x != y]: ",x)

View File

View File

@ -0,0 +1,138 @@
# In this notebook, you will simulate a system with of three nuclei AA , BB and CC where AA decays into BB and BB decays into CC . If exposed to a neutron flux nucleus CC can be activated into a nucleus AA .
import numpy
from matplotlib import pyplot as plt
import random
# Implement a function that tells whether a transition has occured,
# based on the transition probability and a random number. Use the random number r from random.random()
# and use the procedure described in the notes so that the checks can work in a reproducible way.
def has_transitioned(p):
r = random.random()
return True if p>r else False
random.seed(9867)
assert [ has_transitioned(0.5) for i in range(10)] == [False, False, True, False, False, False, False, True, False, True]
def evolveOne(currentState, rules):
# YOUR CODE HERE
for r in rules:
if currentState == r[0]:
return r[1] if has_transitioned(r[2]) else r[0]
else:
continue
else:
return currentState
# these tests are worth 1 mark
alwaysDecayRules = [
('A', 'B', 1.0),
('B', 'C', 1.0)
]
assert evolveOne('A', alwaysDecayRules) == 'B'
assert evolveOne('B', alwaysDecayRules) == 'C'
# these tests are worth 2 mark
random.seed(112211)
testRules = [
('A', 'B', 0.33),
('B', 'C', 0.75)
]
assert evolveOne('A', testRules) == 'A'
assert evolveOne('A', testRules) == 'A'
assert evolveOne('A', testRules) == 'A'
assert evolveOne('A', testRules) == 'A'
assert evolveOne('A', testRules) == 'B'
assert evolveOne('B', testRules) == 'B'
assert evolveOne('B', testRules) == 'C'
assert evolveOne('B', testRules) == 'C'
assert evolveOne('B', testRules) == 'C'
assert evolveOne('B', testRules) == 'C'
# with no rules there should be no change
assert evolveOne('C', testRules) == 'C'
# Now implement a function that takes a list of states and transition them according to the rules passed as argument.
# This function should return a new vector of states, it should not modify the state passed as an argument!
def evolveMany(states, rules):
newState = []
# YOUR CODE HERE
for s in states:
newState.append(evolveOne(s,rules))
return newState
# these tests are worth 1 mark
random.seed(112287)
testRules = [
('A', 'B', 0.33),
('B', 'C', 0.75)
]
initialTestArray = ['A','B','C']*5
evolvedTest = evolveMany(initialTestArray, testRules)
targetArray = ['B', 'C', 'C', 'A', 'C', 'C', 'A', 'B', 'C', 'A', 'C', 'C', 'B', 'C', 'C']
assert evolvedTest == targetArray
# checks the initial array is left unchanged
assert initialTestArray == ['A','B','C']*5
# Define a function that evolves a system that starts with initial amounts NA, NB and NC of AA ,
# BB and CC nuclei and evolved it in n_timestep from time t=0t=0 to t=tmaxt=tmax .
# The function should return three arrays, one for each atom type, of the number of nuclei
# of that type at each time step. Each array should contain n_timestep+1 elements including the initial amount.
def evolve_system(NA, NB, NC, rules, n_step):
state = (['A'] * NA)+(['B'] * NB)+(['C'] * NC)
A_count = numpy.empty(n_step + 1, dtype=int)
B_count = numpy.empty(n_step + 1, dtype=int)
C_count = numpy.empty(n_step + 1, dtype=int)
# YOUR CODE HERE
A_count[0] = NA
B_count[0] = NB
C_count[0] = NC
for i in range(n_step):
state = evolveMany(state, rules)
A_count[i+1] = state.count('A')
B_count[i+1] = state.count('B')
C_count[i+1] = state.count('C')
return A_count, B_count, C_count
# these tests are worth 2 marks
rules = [
('A', 'B', 0.0033),
('B', 'C', 0.0075),
('C', 'A', 0.009)
]
r1, r2, r3 = evolve_system(0, 0, 250, rules, 17)
assert len(r1) == 18
assert len(r2) == 18
assert len(r3) == 18
# these tests are worth 2 marks
testrules = [
('A', 'B', 0.086),
('B', 'C', 0.075),
('C', 'A', 0.19)
]
random.seed(9485)
r1, r2, r3 = evolve_system(200, 200, 200, testrules, 20)
print(r1)
print(r2)
print(r3)
assert (r1 == [200, 213, 233, 250, 258, 251, 266, 263, 259, 260, 265, 259, 256,
255, 258, 256, 259, 253, 249, 247, 253]).all()
assert (r2 == [200, 198, 201, 206, 205, 214, 214, 212, 216, 221, 225, 234, 236,
238, 234, 235, 231, 245, 253, 256, 252]).all()
assert (r3 == [200, 189, 166, 144, 137, 135, 120, 125, 125, 119, 110, 107, 108,
107, 108, 109, 110, 102, 98, 97, 95]).all()

0
homework/__init__.py Normal file
View File

View File

@ -3,10 +3,6 @@ import numpy as np
x = ['北京', '上海', '深圳', '广州']
y = [60000, 58000, 50000, 52000]
plt.plot(x, y)
plt.show()
plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False #用来正常显示负号

View File

@ -2,6 +2,10 @@
import numpy as np
nparr = np.array([i for i in range(10)])
np.zeros(10)
print(nparr,)
a = np.zeros(10)
f = np.zeros(10,dtype=float)
n = np.full((3,5),44)
r = np.random.randint(0,100,size=(3,5))
r2 = np.random.random((3,5))
x = np.linspace(0,100,50)
print(nparr,a,f,n,r,r2,x)

View File

@ -17,7 +17,7 @@ import matplotlib.pyplot as plt
# 从雅虎获得股票数据
# pip install pandas_datareader
# import data reader package
# import data reader 1.14 package
import pandas_datareader as pdr
# read data from Yahoo! Finance for a specific

View File

@ -0,0 +1,4 @@
for i in range(1,9):
for j in range(1,i+1):
print(f"{i}*{j} = {i*j} ", end = "")
print("")

25
实验/1.1 猜数字.py Normal file
View File

@ -0,0 +1,25 @@
# 随机数的处理
# 综合练习---猜数字
# 计算机要求用户输入数值范围的最小值和最大值。
# 计算机随后“思考”出在这个范围之内的一个随机数,
# 并且重复地要求用户猜测这个数,直到用户猜对了。
# 在用户每次进行猜测之后,计算机都会给出一个提示,
# 并且会在这个过程的最后显示出总的猜测次数。这
# 个程序包含了几种类型的我们学过的 Python 语句,例如,输入语句、输出语句、赋值语句、循环和条件语句
import random
smaller = int(input("Enter the smaller number: "))
larger = int(input("Enter the larger number: "))
myNumber = random.randint(smaller, larger)
count = 0
while True:
count += 1
userNumber = int(input("Enter your guess: "))
if userNumber < myNumber:
print("Too small")
elif userNumber > myNumber:
print("Too large")
else:
print("You've got it in", count, "tries!")
break

0
实验/__init__.py Normal file
View File

View File

@ -44,7 +44,7 @@ def LassoRegression(degree, alpha):
("std_scaler", StandardScaler()),
("lasso_reg", Lasso(alpha=alpha))
])
lasso1_reg = LassoRegression(20, 0.01)
lasso1_reg = LassoRegression(20, 0.1)
lasso1_reg.fit(X_train, y_train)
y1_predict = lasso1_reg.predict(X_test)
mean_squared_error(y_test, y1_predict)