前面的丢失了
0308
if height<=1.3:
elif hieght<=1.5:
else:
1.字符串 变量可以理解为一个标签
# string
apple + "123" = apple123
apple * 2 = appleapple
# dir 获取一个对象的所有属性和方法
dir(apple)
apple.upper() = APPLE
"APPLE".lower() = apple
phone = 123456
phone.startwith("123") # Ture
phone[0:3] = pho # catch first three characters
phone[3:] = ne
# translate
str(123)
int("123")
price = 11
print(f"your should pay {price}.") # {price:.2f} 保留两位小数
# ASCII GBK/UTF-8(ordinary) 处理汉字的编码
ord('a') = 97
'apple' < 'banana' # 排序也是按照ASCII, Ture
# 后面跟着括号的一般都叫做函数
print(3+5) # 8
# module
from math import sin
sin(math.pi) = 1.22e-16
# create your own function
# you can use print to test your program
def test(a,b) # input a,b
print("----------")
if a>b:
return a # output a
else:
return b
x = int(input"x")
y = int(input"y")
result = test(x,y) # run and store the function
print(result)
from module1 import test
import * # import everything
0315
pycharm 可以有local history展示你所有的编辑操作
# 返回多个值的函数 raise Error 快捷键ctrl+#
'''
:param total:打折前的价格
:return:打折后的价格
'''
def calcDiscount(total)
if total<0:
raise RuntimeError("total can't be negative!") # 停止执行并报错
if total<200:
r=1
elif total<500:
r=0.95
else:
r=0.9
d=r*total
return r,d
x,y=calcDiscount(1000)
print(x,y)
循环结构:
1.while
# sum
n=100
sum=0
i=1
while i<=n: # ture 的话就continue
if i%2==1:
sum+=i
else:
sum+=i*1
i+=1
print(sum)
# 买啤酒
beers=5
lids=0
bottles=0
total=0
while beers>0:
# drink
lids+=beers
bottles+=beers
total +=beers
beers=0
print("喝:",total, beers, lids, bottles)
# exchange
beers += lids // 4
beers += bottles // 2
lids %= 4
bottles %= 2
2.for循环 0322
for i in range(10):
print(i)
# 0 1 2 3 4 5 6 7 8 9 (能用for就用)
# 1.4 break continue
# caculate credits
def calcCredit():
total=0
count=0
while Ture:
credit=float(input(f"请输入第{count+1}门课的学分:"))
if credit<=0
return total,count
total += credit
count+=1
total,count = calcCredit()
print(f"一共{count}门课程,总学分为{round(total,1)}")
# 2.1pension
r=0.025
account=0
for y in range(10):
# 利息
account+=account*r
# 存入一万
account+=10000
print(f"账户金额{account:.2f}")
# insurance
r=0.025
account=0
for y in range(26):
# 存钱
account+=account*r
# 取钱
if 0<=y<=8:
account+=15250
if 15<=y<17:
account-=10000
if 18<=y<=21:
account-=20000
if y==25:
account
数值计算(求近似解)
# 近似求积分
delta=0.00000001
def integral(a,b,f)
area=0
x=a
while x<=b:
area+=f(x)*delta
x+=delta
return area
import math
print(integral(0,math.pi/2,math.sin))
# 牛顿法求方程的根
import math
a=float(input("a="))
x=a
delta=0.000001
while Ture:
x1=x/2+a/x/2
print(x,x1)
if math.fabs(x1-x2)<delta
break
x=x1
print(x)
# peak 梯度下降法
# 梯度是矢量,可以求两个分量间接求梯度
# 求圆周率不详细说
# 蒙特卡洛
n=500000
count=0
for i in range(n):
x=random.uniform(-1,1)
y=random.uniform(-1,1)
if x*x+y*y<1:
count+=1
print(4*count/n)
# 用蒙特卡洛法去做 (了解并掌握?)
# 蒙特卡洛
n=500000
count=0
for i in range(n):
sale = random.normalcariate(30000,10000)
if sale<0:
sale=0
price = random.normalcariate(6,1)
if price<0:
price=0
r = random.normalcariate(0.1,0.02)
if r<1:
r=0
profit = sale * price - 200000*(1+r)
if profit<0:
count += 1
print(f"亏损可能性:{count/n*100:.2f}%")
0329 :
程序计算的中间结果是用变量保存的
数据结构
1.列表和元组
# 直接用四重循环
for a in range(1,6):
for b in range(1,6):
if a==b: # 排除相同的情况
continue
for c in range(1,6):
if c==b or c==a:
continue
for d in range(1,6):
if d==a or d==b or d==c:
continue
e=15-a-b-c-d
c_a=c_b=c_c=c_d=0 # 判断是否正确的新变量
if b=2:
c_a+=1
if e=4:
c_a+=1
if c=1:
c_b+=1
...
if c_a=1 and c_b=1 and c_c=1 and c_d=1 and c_e=1:
print(f"a={a},b={b},...")
六、结构化编码(排序,分支和循环)
列表是连续存放着无数个标签
# visit
y = [1,2,3,4,5]
y[0] = 1 # y[4//2]也可以,但是括号里面必须要是整数
y[-1] # 倒数第一个元素,5
# 变量和列表性质相似,运算共通
lsty=[1,23,45]
len(lsty) # 获取元素个数
lsty=lsty+lstb # 首尾相接两个列表
# 标签可以不用类
x=[1,2,3,'hi']
x[0]=y # x=[[1,2,3,4,5],1,2,3,'hi']
y.append(5) # 追加一个5
y.insert(0,50) #在第一个东西后面加一个50这个元素,用help(y,insert)查询用法
del y[2] # 删掉第三个元素
len(y) # y里面有几个元素
y[1:-1] #不包括倒数第一个,包括第二个等
y[:] #从头取到尾
x=y[:] #让x复制y里面的东西,但是不关联
#caculate 对列表的遍历/迭代访问
y = [1,2,3]
n = len(n)
sum = 0
for i in range(n):
sum+=y[i]
print(sum)
# 比较常用的遍历方法
y = [1,2,3]
n = len(y)
sum = 0
for x in y:
sum += x
print(sum)
1.4.1 关键词过滤
block_words = ["sb","傻瓜"]
def shouldBeBlocked(msg):
for s in block_words:
if msg.find(s) >= 0:
return True
return Flase
text = input()
if shouldBeBlocked(text):
print("你说话不文明")
1.4.2 筛法求素数
n = 500
lst = List(range(2,n+1)) # 1不是素数
print(lst) # 先打印出来看看
i = 0 # 初始化下标
while i<len(lst): # 遍历列表
x = lst[i] # 取遍所有的数
j = i+1 # 从下一个数开始找素数
while j<len(lst): # len(lst)是会变的
if lst[j]%x == 0: # 也就是说lst[j]可以整除以小于他的下标的数
del lst[j] # 删完之后后面的数字会前移
else:
j+=1 #继续检验下一个
i+=1 #取下一个i
print(lst)
1.4.5 约瑟夫问题
# 1.4.5
alive=[1]*42
print(alive)
dead=[]
c=0
while len(dead)<41:
i+=1
if i>41:
i=1
if alive[i]==1:
c+=1
if c==3:
alive[i]==0
c=0
deade.sppend(i)
print(dead)
0406 对象
# 类(class)和对象
class Student
def __init__(self,id,name,score)
# 两个下划线开头和结尾,一般第一个都叫做self,self是创建一个对象
# 把id赋给了self对象的id属性
self.id = id
self.name = name
self.score = score
def __str__(self,id,name,score)# 这样才能输出s1储存的内容
return f"id:{self.id} - name:{self.name} - score:{self.score}"
s1 = Student(12034,"Tim",100) # 生成了一个有三个属性的对象
print(s1.id) #可以直接访问
s1.id = 2000 #可以直接更改
s2=s1
s2.name = 'Tom'
print(s1,name) # 也是Tom,s2=s1,也就是说s2指向了s1
print(s1) # 不定义__str__的话就是寻址
print(s1) # 定义后才能输出内容
# (首选方式)便捷:类的模板 dataclass(会自动创建init、str)
from dataclass import dataclass
@dataclass
class Student:
id:int
name:str
score:float
# 图书馆管理系统 类的首字母大写,变量名小写,列表名字一般是复数
from dataclass import dataclass
@dataclass
class User:
id:str
name:str
TYPE:str # 不能用type因为是关键字
borrowed:int
def canBorrow(user:User):
if user.TYPE == "教师"
return 10-user.borrowed
return 5-user.borrowed
u1=User("1110","Tim", "教师", 3)
print(canBorrow(u1))
# 储存多个对象
users=[User("123"),User("...")]
# dataclass 可以存放列表
from dataclass import dataclass
from typing import List
@dataclass()
calss Student:
id:str
name:str
score:float
clazz:Clazz #用班级属性储存他属于哪个班
@dataclass()
class Clazz:
id:str
name:str
students:List[Student]
对象复制不说,文件的输入和输出
file=open(filename,mode="r",encoding="GBK")
# 文件的路径就是filename,只有同一个路径才能直接访问文件名
# mode表示读取还是写 w叫做覆盖写
# 中文常用GBK和UTF-8
file.close() # 读完记得要关闭
# 自动关闭
with open(filename,mode="r",encoding="GBK") as file:
# excel 下列program不完整
import csv
from Deciamal import decimal
with open(filename,mode = "r",encoding="GBK")as file: # filename是文件的路径
reader = csv.reader(file)
next(reader) # 跳过表头
for row in reader:
name = row[0]
price = Decimal(row[1]) # 转化为十进制数字
quantity = int(row[2])
sale = Sale(name,price,quantity)
sales.append(sale) # 每读一行都加到sales列表里面去
print(sales) # 看你读出来的内容对不对
“w”是覆盖写
计算平均分:
total/n:.2f
计算最高分:
# 找到所有的最高分
def which_max_score(scores):
max_score = score[0].score # 一开始把第一个同学当作最高分
results=[ ]
for score in scores:
if score.score>max_score: # 如果比最大分还要大就替换
max_score = score.score
results = [score]
elif score.score == max_score:
results.append(score)
return results
# 找到列表里面所有90分的人
def count90(scores):
count=0
for s in scores:
if s.score >= 90:
count+=1
return count
counts=[0]*11
# 找到列表里面各个分段的人
for s in scores:
i=int(s.score // 10)
counts[i]+=1
print(counts)
找到最高分所在的位置:
0412
4.2 分段计数
elif和if不影响,简化版计数:
4.3
filename = 'xxx.csv'
sales = read_csv(filename)
print(sale) # 可以看到有几个种类,以及他们的数量
stats_name = 'bread'
total_quantity = 0
total = 0
for s in sales:
if s.name === stats_name:
total_quantity += s.quantity
total += s.quantity * s.price
print(total_quantity, total)
筛选操作
# 筛选可以是任意的
notpassed=[]
for s in scores:
if s.score < 60:
notpassed.append(s)
print(notpassed)
查找
# 按照条件/下标查找 4-2-1
def search(key_name,scores):
for s in scores:
if s.name == key_name:
return s
return None
# 按照姓名折半查找
def which(key_name,scores):
for i in range(len(scores)):
if scores[i].name == key_name:
return i
return None
print(scores)
print(search("Tim",scores))
# 折半法查找,数据量比较大的时候顺序查找效率低下 5-1-1
def which_binary_search(key_id,scores)
start = 0
end = len(scores)-1
while start<=end:
mid = (start+end) // 2
if scores[mid].id == key_id:
return mid
elif scores[mid].id < key_id:
end = mid - 1
else:
start = mid + 1
return None
print(which_binary_search("166",scores))
# 二分法查找
排序
lst=[1,2,3,4,50]
lst2=[x*x for x in lst]
# lst2=[1,4,8,16,2500]
lst3=[x*x for x in lst if x<=40]
# lst3=[1,2,3,4]
0420
6.1 dictionary
dic={'T':100,'A':87} # 花括号是字典,[]是实列表
dic[T] # 100
'D' in dic # 判断D在不在里面
del dic['T']
n=[A]
dic[n] # 100
dic[lst[0]] # 这个也可以访问
for x in lst:
print(x) # print(dic[x])访问里面的元素
# 读取一个csv文件
key = 'A'
if key in scores:
print("YES")
else:
print("No")
# 插入字典去查找
def gen_id_dic(scores):
dic = {}
for n in scores:
s=scores[n]
dic[s.id]=s
return dic
scores.id = gen_id_dic(scores)
print(scores_id)
scores['T'].score=100
print(scores_id['123']) #查找id为123的
6.2 集合Collection
# 字典可以代替集合,了解就行
filename = '.csv'
sales = read_csv(filename)
print(sales)
s=set()
for sale in sale:
s.add(sale.name)
print(s)
print(list(s))
???????
数据结构是大量数据在内存中的存放形式
存放形式不同,处理方式和速度不同
程序=数据结构+算法
函数是相对独立的功能单位
print(gobals())函数就是全局作用域
缺口函数:def test(a,b) 可以是test(b=6)
fff=test -> fff(3,5)
True是从小到大,False是从大到小(返回了一个新的列表,原来的列表不变)
s返回s.score reverse表示函数排序方法
# 计算n的阶层 用函数和递归
def factorial(n):
if n==0:
return 1
return n*factorial(n-1)
print(factorial(5))
递归调用的本质是计算代码被重复执行,和循环类似
循环是有循环条件的,递归必须有一个递归结束条件:n==0
# 计算总和
lst=[35,72,96,81,49]
def sum(lst,n):
if n==0:
return 0
return sum(lst,n-1)+lst[n-1]
print(sum(lst,len(lst)))
# 计算所有学生里面的最高分 1:20:27
lst=[35,72,96,81,49]
def max(lst,n):
if n==1:
return lst[0]
a=max(lst,n-1)
b=lst[n-1]
if a>b:
return a
else:
return b
print(max(scores,len(scores)))
# 计算有多少个人不及格
# 1.3 简单递归
n = 3的时候可以得到三个循环
0426
递归求最大值
# 斐波那契额数列 a这个列表就是一个备忘录,可以避免重复
# 动态规划本质是递归
a=[0]*1000
def fib(n):
if a[n]!=0:
return a[n]
if n==1 or n==2:
a[n]=1
else:
a[n]=fib(n-1)+fib(n-2)
return a[n]
print(fib(10))
去文件夹里面找文件