defParse(str):#将str解析成字典表示的多项式,并返回# 请在此添加实现代码 ## ********** Begin *********#
pos =0
slen =len(str)
poly={}while(pos<slen):
a =0if(str[pos]=='+'):
a =int(str[pos+1])else:
a =-int(str[pos+1])
po =int(str[pos+4])
poly[po]= a
pos +=5return poly
# ********** End **********#defEval(poly,x):#带入x到poly,并打印计算结果# 请在此添加实现代码 ## ********** Begin *********#sum=0for power in poly.keys():sum+= poly[power]*x**power
print(sum)# ********** End **********#
读取文件数据到字典 - 城市温度对比
defRead(path):#解析文件内容成一个字典# 请在此添加实现代码 ## ********** Begin *********#
infile =open(path,'r')
temps ={}for line in infile.readlines():
city,temp = line.split()
city = city[:-1]
temps[city]=float(temp)
infile.close()return temps
# ********** End **********#
文件读取与字符串处理 - 可视化显示股票数据
import matplotlib as mpl
mpl.use('Agg')import matplotlib.pyplot as plt
import datetime
defDraw():
appl ="step3/AAPL.csv"#苹果
google ="step3/GOOG.csv"#谷歌
ms ="step3/MSFT.csv"#微软#在此绘制折线图# 请在此添加实现代码 ## ********** Begin *********#
plt.xticks(rotation =45)
appdate,appopens = Read(open(appl))
plt.plot(appdate,appopens,color ='red',linewidth =1.0,label="appl")
gogdate,gogopens = Read(open(google))
plt.plot(gogdate,gogopens,color ='green',linewidth =1.0,label="goog")
msdate,msopens = Read(open(ms))
plt.plot(msdate,msopens,color ='blue',linewidth =1.0,label="ms")
plt.legend(["Apple","Google","Microsoft"])
plt.ylabel("Open")
plt.savefig("step3/output/data.png")#如果有必要,可以增加别的函数协助完成任务,可在此添加实现代码 # ********** Begin *********#defRead(file):
dates=[]
opens=[]file.readline()for line infile.readlines():
i1 = line.index(",",0,len(line))
dt = datetime.datetime.strptime(line[0:i1],"%Y-%m-%d").date()
dates.append(dt)
i2 = line.index(",",i1+1,len(line))
opens.append(float(line[i1+1:i2]))file.close()return dates,opens
# ********** End **********#
Python 计算思维训练——字典和字符串(二)
字符串处理 - 从文件读取对的数据
defRead(path):#解析文件中的数据对,添加到列表中并返回# 请在此添加实现代码 ## ********** Begin *********#file=open(path,'r')
lines =file.readlines()
pairs =[]for line in lines:
words = line.split()for word in words:
word = word[1:-1]
n1,n2 = word.split(',')
n1 =float(n1)
n2 =float(n2)
pair =(n1,n2)
pairs.append(pair)file.close()return pairs
# ********** End **********#
多级字典 - 天气数据读取与输出
defParse():
path ="step2/oxforddata.txt"#将文件内容解析成一个多级字典,并返回# 请在此添加实现代码 ## ********** Begin *********#
infile =open(path,'r')
data ={}#跳过头七行for i inrange(7):
infile.readline()for line in infile:
columns = line.split()
year =int(columns[0])
month =int(columns[1])if columns[-1]=='Provisional':del columns[-1]for i inrange(2,len(columns)):if columns[i]=='---':
columns[i]=Noneelif columns[i][-1]=='*'or columns[i][-1]=='#':#去掉后缀
columns[i]=float(columns[i][:-1])else:
columns[i]=float(columns[i])
tmax, tmin, af, rain, sun = columns[2:]ifnot year in data:
data[year]={}
data[year][month]={'tmax': tmax,'tmin': tmin,'af': af,'rain':rain,'sun': sun}return data
# ********** End **********#