作业代码

#购物车

li = [
    {'name':'苹果','price':10},
    {'name':'香蕉','price':20},
    {'name':'西瓜','price':30}
]
#把货品放在货架上
money = '300'   #钱
shoop_dic = {}   #购物车 key:商品  value  : 价钱
print("欢迎光临")
for i,k in enumerate(li):
    print('序号{},商品{},价格{}'.format(i,k['name'],k['price']))
chose = input("请选择你的商品序号:")
if int(chose) >= 0 and int(chose) <= len(li):
    num = input("你要购买的商品数量:")
    if num.isdigit():
        if int(money) > li[int(chose)]['price'] * int(num):
            money = int(money) - li[int(chose)]['price'] * int(num)
            if li[int(chose)]['name'] in shoop_dic:
                shoop_dic[li[int(chose)]] = shoop_dic[li[int(chose)]] + int(num)
            else:
                shoop_dic[li[int(chose)]['name']] = int(num)
            print('购物车商品{},剩余钱{}'.format(li[int(chose)]['name'], money))
        else:
            print("钱不够")
else:
    print("序号错误")
购物车

 

#用户注册登录代码
a = input('1 注册,2 登陆:')

def denglu():
    username = input("请输入用户名:")
    passwd = input("请输入密码:")
    with open('user_list') as f2:
        for line in f2:
            user,pwd = line.split('|')
            if username == user and passwd == pwd:
                print("登录成功")
            else:
                print("登录失败")




def zhuce():
    username = input("请输入用户名:")
    passwd = input("请输入密码:")
    with open('user_list','w',encoding='utf-8') as f1:
        f1.write('{}|{}'.format(username,passwd))
    print("注册成功")

if a == '1':
    zhuce()
elif a == '2':
    denglu()
else:
    print("输入有误")
注册登录

 

#编写装饰器,为多个函数加上认证功能
#要求登录成功一次,后续的函数都无需再输入用户名和密码

FLAG = False
def login(func):
    def inner(*args,**kwargs):
        #装饰的内容
        global FLAG
        if FLAG:
            ret = func(*args, **kwargs)
            return ret
        else:
            username = input("name:")
            passwd = input("passwd:")
            if username == 'xiao' and passwd == '123':
                print("成功")
                FLAG = True
                ret = func(*args,**kwargs)
                return ret
            else:
                print("登录失败")
    return inner

@login
def  shoplist_add():
    print("增加一件物品")
@login
def  shoplist_del():
    print("删除一件物品")

shoplist_add()
shoplist_del()
代码

 #生成器,从文件中读取内容,在没一次读取到的内容之前加上“###” 之后返回用户

def neirong(p):
    with open(p,encoding='utf-8') as f:
        while True:
            g = f.readline()
            yield g
ff = neirong('file')
print('****' + ff.__next__())
print('****' + ff.__next__())
print('****' + ff.__next__())

-----------------------------------------------------
def check_file(p):
    with open(p, encoding='utf-8') as f:
        for i in f:
            yield '***' +i
for i in check_file('file'):
    print(i.strip())
View Code

#处理文件,用户指定查找的文件和内容,将文件中包含要查找的内容每一行输出到屏幕

def check_file(a,b):
    with open(a,encoding='utf-8') as f:
        for i in f.readline():
            if b in i:
                yield i
g = check_file('file','xiao')
for i in g:
    print(i)
View Code

 # 接收用户输入页码,每页5条,仅输出当页的内容

# with open('file',encoding='utf-8') as f:
#     l = f.readlines()
# page_in = int(input('输入第几页:'))
# pages,mod = divmod(len(l),5)
# if mod != 0:
#     pages += 1
#
# if page_in > pages or page_in <= 0:
#     print("输入有误")
# elif page_in == pages and mod != 0:
#     for i in range(mod):
#         print(l[(page_in - 1) *5 +i].strip())
# else:
#     for i in range(5):
#         print(l[(page_in - 1) * 5 +i].strip())
View Code
# 3.用map来处理字符串列表,把列表中所有人都变成sb,比方alex_sb
name=['alex','wupeiqi','yuanhao','nezha']
# def f(p):
#    return (p +"_sb")
# ret = map(f,name)
# for i in ret:
#     print(i)

# ret = map(lambda p: p + '_sb',name)
# for i in ret:
#     print(i)
View Code
#4.用filter函数处理数字列表,将列表中所有的偶数筛选出来
# num = [1,3,5,6,7,8]
# ret = filter(lambda p:p % 2 == 0,num)
# for i in ret:
#     print(i)
# 5.随意写一个20行以上的文件
# 运行程序,先将内容读到内存中,用列表存储。
# 接收用户输入页码,每页5条,仅输出当页的内容
# with open('file',encoding='utf-8') as f:
#     l = f.readlines()
# page_in = int(input('输入第几页:'))
# pages,mod = divmod(len(l),5)
# if mod != 0:
#     pages += 1
#
# if page_in > pages or page_in <= 0:
#     print("输入有误")
# elif page_in == pages and mod != 0:
#     for i in range(mod):
#         print(l[(page_in - 1) *5 +i].strip())
# else:
#     for i in range(5):
#         print(l[(page_in - 1) * 5 +i].strip())
View Code
# 6.如下,每个小字典的name对应股票名字,shares对应多少股,price对应股票的价格
portfolio = [
     {'name': 'IBM', 'shares': 100, 'price': 91.1},
     {'name': 'AAPL', 'shares': 50, 'price': 543.22},
     {'name': 'FB', 'shares': 200, 'price': 21.09},
     {'name': 'HPQ', 'shares': 35, 'price': 31.75},
     {'name': 'YHOO', 'shares': 45, 'price': 16.35},
     {'name': 'ACME', 'shares': 75, 'price': 115.65}
]

# 6.1.计算购买每支股票的总价
# def f(dic):
#     ret = {dic['name'] : round(dic['shares'] * dic['price'],2)}
#     return ret
#
# ret = map(f,portfolio)
# for i in ret:
#     print(i)

# 6.2.用filter过滤出,单价大于100的股票有哪些
# def f(dic):
#     if dic['price'] > 100:
#         ret = {dic['name']:dic['price']}
#         return ret
# ret = filter(f,portfolio)
# for i in ret:
#     print(i)

# ret = filter(lambda dic:dic['price'] > 100,portfolio)
# print(list(ret))
View Code
#员工信息查询
ret = 'select name,age where age > 20'
ret = ret.split('where')
con = ret[1]
key1,val1 = con.split('>')
ver = ret[0].split('select')
username,userage = ver[1].split(',')
name = username.strip()
age = userage.strip()
key = key1.strip()
val = val1.strip()

#打开文件
dic = {'name':1,'age':2,'haoma':3,'gongzuo':4}
def openfile(p):
    with open(p,encoding='utf-8') as f:
        ret = f.readlines()
        return ret


#分析
def fenxi(age,num):
      g = openfile('file1')
      for i in range(len(g)):
          ret = g[i].split()
          if int(ret[dic[age]]) > int(num):
              yield ret

# # #展示
def  zhanshi(name,age):
    d = fenxi(key,val)
    for i in d:
        name1 = i[dic[name]]
        age1 = i[dic[age]]
        yield name1,age1
g = zhanshi(name,age)
for i in g:
    print(i)
#员工信息查询
#阶乘  10*9*8*7*6*5*4*3*2*1

def func(p):
    if p == 1:
        return 1
    return p * func(p-1)
ret = func(9)
print(ret)
阶乘
# 斐波那契  # 问第n个斐波那契数是多少
#1,1,2,3,5,8
def func(p):
    if p == 1 or p == 2:
        return 1
    return func(p - 1) + func(p -2)   # func(3) + 1 # func(2)+func(1) +1 # 1 + 1 +1 =3
ret = func(20)
print(ret)
# 斐波那契 # 问第n个斐波那契数是多少

 

import re
import json
from urllib.request import urlopen

def getPage(url):    # 下载到一个url网站的信息
    response = urlopen(url)
    return response.read().decode('utf-8')   # 信息一般挡下来是字节的 ,将其转为utf-8编码

def parsePage(s):     #匹配信息,反悔生成器 ,迭代自己想看的信息
    com = re.compile(
        '<div class="item">.*?<div class="pic">.*?<em .*?>(?P<id>\d+).*?<span class="title">(?P<title>.*?)</span>'
        '.*?<span class="rating_num" .*?>(?P<rating_num>.*?)</span>.*?<span>(?P<comment_num>.*?)评价</span>', re.S)

    ret = com.finditer(s)
    for i in ret:
        yield {
            "id": i.group("id"),
            "title": i.group("title"),
            "rating_num": i.group("rating_num"),
            "comment_num": i.group("comment_num"),
        }


def main(num):
    url = 'https://movie.douban.com/top250?start=%s&filter=' % num
    response_html = getPage(url)          #读取url页面信息
    ret = parsePage(response_html)       #正则 表达式匹配
    print(ret)
    f = open("move_info7", "a", encoding="utf8")   #打开一个文件

    for obj in ret:   #把url读取的循环写入文件中
        print(obj)
        data = str(obj)
        f.write(data + "\n")
    f.close()

count = 0
for i in range(10):  # 有10页 进行循环
    main(count)
    count += 25  #一页 25个记录
爬豆瓣电影的评分

 

import re
def rep(exp):
    if '--' in exp:
        return exp.replace('--','+')
    elif '+-' in exp:
        return exp.replace('+-','-')
    else:
        return exp
def ji_son(exp):
     #用来计算括号内表达式的乘除
     if '/' in exp:
         a,b = exp.split('/')
         return str(float(a)/float(b))
     elif '*' in exp:
         a,b = exp.split('*')
         return str(float(a)*float(b))
def no_kuohao(exp):
    exp_new = exp.strip('()')                #给传来的(-40/5) 去括号 -40/5
    while True:
        ret = re.search('\d+\.?\d*[*/]-?\d+\.?\d*',exp_new)
        if ret:
            ret1 = ret.group()       #40/5
            #print(ret1)
            ret1_ji = ji_son(ret1)    #计算    8.0
            #print(ret1_ji)
            zhi = exp_new.replace(ret1,ret1_ji)     #-8.0
            #print(zhi)
            exp_new = rep(zhi)
        else:
            ret = re.findall('-?\d+\.?\d*',exp_new)
            sum = 0
            for i in ret:
                sum = float(sum) + float(i)
            return str(sum)
def man(express):      #主函数
    new = express.replace(' ','')     #去空格
    while True:
        ret = re.search('\([^()]+\)',new)  #取到一个括号
        if ret:
            ret1 = ret.group()
            #print(ret1)                           #(-40/5)
            new_son = no_kuohao(ret1)            #对括号内的表达式计算

            ji = new.replace(ret1,new_son)
            #print(ji)
            new = rep(ji)
        else:
            print("没有括号",new)
            new_son1 = no_kuohao(new)
            return new_son1
express = " 1 - 2 * (( 60 -30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 *568/14))) - (-1*3)/(16-3*2)"
func = man(express)
print(func)
计算器

 



 

转载于:https://www.cnblogs.com/huxl1/p/10804317.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
非常抱歉,我无法直接提供完整的 MATLAB 大作业代码,因为我无法运行外部代码。但是,我可以为你提供一些指导和帮助,以便你能够自己完成大作业。 首先,你需要明确大作业的要求和目标。然后,根据要求确定需要使用的 MATLAB 工具箱和函数,并进行必要的数据预处理和分析。在编写代码时,建议按照模块化的方式进行,将不同的任务分解成函数,并在主程序中调用这些函数。 以下是一些可能有助于你完成大作业的一般步骤: 1. 了解问题:仔细阅读作业要求,确保你理解问题的核心内容和目标。 2. 数据处理:根据要求,获取或生成所需的数据,并进行必要的预处理,例如数据清洗、归一化或平滑。 3. 算法选择:根据问题的性质选择合适的算法和方法。MATLAB 提供了许多内置函数和工具箱,可以帮助你完成各种任务。 4. 编写代码:根据所选算法和方法,编写 MATLAB 代码。尽量保持代码简洁、易读和可维护性。 5. 调试和测试:逐步验证每个函数的正确性,确保代码能够正常运行。可以使用 MATLAB 的调试工具来帮助你找出可能的错误和问题。 6. 结果分析:根据作业要求,对结果进行分析和解释。使用 MATLAB 的绘图函数可以帮助你可视化结果。 请注意,以上步骤是一般性的指导,具体步骤可能因大作业的要求和性质而有所不同。如果你能提供更多关于大作业的具体信息,例如问题的描述、数据类型和预期输出,我可以给予更具体的帮助。 希望这些指导对你有所帮助!如果你有任何进一步的问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值