Python 计算思维训练——字典和字符串

Python 计算思维训练——字典和字符串(一)

  1. 字典基本操作 - 使用字典表示和计算多项式
def Parse(str):
    #将str解析成字典表示的多项式,并返回
    #   请在此添加实现代码   #
    # ********** Begin *********#
    pos = 0
    slen = len(str)
    poly={}
    while(pos<slen):
        a =0
        if (str[pos] == '+'):
            a = int(str[pos+1])
        else:
            a = -int(str[pos+1])
        po = int(str[pos+4])
        poly[po] = a
        pos +=5
    return poly
    # ********** End **********#

def Eval(poly,x):
    #带入x到poly,并打印计算结果
    #   请在此添加实现代码   #
    # ********** Begin *********#
    sum = 0
    for power in poly.keys():
        sum += poly[power]*x**power
    print(sum)
    # ********** End **********#
  1. 读取文件数据到字典 - 城市温度对比
def Read(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 **********#
  1. 文件读取与字符串处理 - 可视化显示股票数据
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt


import datetime


def Draw():
    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 *********#
def Read(file):
    dates=[]
    opens=[]
    file.readline()
    for line in file.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 计算思维训练——字典和字符串(二)

  1. 字符串处理 - 从文件读取对的数据
def Read(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 **********#
  1. 多级字典 - 天气数据读取与输出
def Parse():
    path = "step2/oxforddata.txt"
    #将文件内容解析成一个多级字典,并返回
    #   请在此添加实现代码   #
    # ********** Begin *********#
    infile = open(path, 'r')
    data = {}
    #跳过头七行
    for i in range(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 in range(2, len(columns)):
            if columns[i] == '---':
                columns[i] = None
            elif 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:]
        if not year in data:
            data[year] = {}
        data[year][month] = {'tmax': tmax, 'tmin': tmin, 'af': af, 'rain':rain, 'sun': sun}
    return data
    # ********** End **********#
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值