笔记汇总(2)

日常笔记,对错自辩,仅供交流学习。

日常笔记,对错自辩,仅供交流学习。

日常笔记,对错自辩,仅供交流学习。

笔记汇总1

3.1 逆序排列

【问题描述】
编写程序对标准输入的10个整数置逆序排列并输出。
【输入形式】标准输入的前十行代表参与计算的十个整数。
【输出形式】标准输出的一行表示逆序后的数组,以空格作为间隔。

L=[]
for i in range(10):
    n=int(input())
    L.append(n)
#print(L)
L.reverse() #逆序(转置)
for i in range(10):
    print(L[i],end=" ")

3.2 整数排序

【问题描述】
输入n的值和n个数,进行排序并输出。

【输入形式】
首先输入整数个数n;接着输入n个整数

【输出形式】
从小到大地输出n个整数

num=int(input())
L=[]
L=list(map(int,input().split()))
# 检查输入的数的数量是否正确
if len(L) != num:
    print("输入的数的数量不正确")
else:
    # 对列表进行排序
    L.sort()
    # 输出排序后的列表
    for i in range(num):
        print(L[i],end=" ")

3.3 模拟火车订票系统

t1 = ('车次', '出发站-到达站', '出发时间', '到达时间', '历时')
t2 = ('T40', '长春-北京', '00:12', '12:20', '12:08')        
t3 = ('T298', '长春-北京', '00:06', '10:50', '10:44')
t4 = ('Z158', '长春-北京', '12:48', '21:06', '08:18')
t5 = ('Z62', '长春-北京', '21:58', '06:08', '8:20')
T = (t2, t3, t4, t5)

#打印所有车次信息
print("{}      {}    {}    {}     {}".format(t1[0],t1[1],t1[2],t1[3],t1[4]))
for i in range(len(T)):
    if i == 0 or i == 3:
        print("{}       {}        {}       {}       {}".format(T[i][0],T[i][1],T[i][2],T[i][3],T[i][4]))
    else:
        print("{}      {}        {}       {}       {}".format(T[i][0],T[i][1],T[i][2],T[i][3],T[i][4]))

def check(c):
    '''
    定义check函数,查询用户输入的车次,返回对应车次信息
    '''
    for t in T:
        for i in t:
            if c == i:
                index = t.index(c)
                return t[index + 1], t[index + 2]
c = input('请输入要购买的车次:\n')
t_person = input('请输入乘车人(用逗号分隔):\n')
re = check(c)
print('你已购%s次列车 %s %s开,请%s尽快换取纸质车票。【铁路客服】' % (c, re[0], re[1], t_person))

3.4 收视率排行榜

TV = [("《Give up,hold on to me》","1.4%"),
      ("《The private dishes of the husbands》","1.343%"),
      ("《My father-in-law will do martiaiarts》","0.92%"),
      ("《North Canton still believe in love》","0.862%"),
      ("《Impossible task》","0.553%"),
      ("《Sparrow》","0.411%"),
      ("《East of dream Avenue》","0.164%"),
      ("《Theprodigal son of the new frontier town》","0.259%"),# 空格The prodigal
      ("《Distant distance》","0.394%"),
      ("《Music legend》","0.562%")]              # 原电视剧列表
TV.sort(key=lambda x:x[1], reverse=True)                 # 对元素的第二个字段进行降序
print('电视剧的收视率排行榜:')
for i in TV:
    print(i[0]+' 收视率:'+i[1])

3.5 《沉默的羔羊》之最多单词

【问题描述】

文件"demo.txt"是《沉默的羔羊》中文版内容,请读入文件内容,分词后输出长度大于2且最多的单词。‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬

如果存在多个单词出现频率一致,请输出按照Unicode排序后最大的单词。

注意:要读入的文件已放入当前目录下,源文件中直接读取此文件即可。

import jieba
from collections import Counter
# 打开并读取文件
with open('demo.txt', 'r', encoding='utf-8') as f:
    text = f.read()
# 使用jieba进行分词
words = jieba.lcut(text)
# 过滤掉长度不大于2的词
words = [word for word in words if len(word) > 2]
# 计算每个词的出现次数
word_counts = Counter(words)
# 找出出现次数最多的词
most_common_words = word_counts.most_common()
# 获取出现次数最多的次数
max_count = most_common_words[0][1]
# 获取所有出现次数最多的词
max_count_words = [word for word, count in most_common_words if count == max_count]
# 按照Unicode排序后选择最大的词
max_word = max(max_count_words, key=lambda word: (word.encode('utf-8')))
print(max_word)

3.6 文本词频统计 – Hamlet

【问题描述】一篇文章,出现了哪些词?哪些词出现的最多?

请统计hamlet.txt文件中出现的英文单词情况,统计并输出出现最多的5个单词,注意:‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬

(1) 单词不区分大小写,即单词的大小写或组合形式一样;‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬

(2) 请在文本中剔除英文标点符号;‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬

(3) 输出5个单词,每个单词一行;‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬

(4) 输出单词为小写形式。

注意:要读入的文件已放入当前目录下,源文件中直接读取此文件即可。

import re
from collections import Counter
# 打开并读取文件
with open('hamlet.txt', 'r') as f:
    text = f.read().lower()
# 移除所有的标点符号
text = re.sub(r'[^\w\s]', '', text)
# 分割文本为单词列表
words = text.split()
# 计算每个单词的出现次数
word_counts = Counter(words)
# 找出出现次数最多的5个单词
most_common_words = word_counts.most_common(5)
# 打印出现次数最多的5个单词
for word, count in most_common_words:
    print(word)

3.7 钓鱼内容字典记账

【问题描述】

三酷猫想利用字典的清晰的键值对关系及灵活操作功能,实现对每天所钓鱼内容的记账过程。

fish_records = {'1月1日':{'鲫鱼':[18,10.5],'鲤鱼':[8,6.2],'鲢鱼':[7,4.7]},
                '1月2日':{'草鱼':[2,7.2],'鲫鱼':[3,12],'黑鱼':[6,15]},
                '1月3日':{'乌龟':[1,71],'鲫鱼':[1,9.8],'草鱼':[5,7.2],'黄鱼':[2,40]}}#所有钓鱼记录
#计算总价格和总数量
n = 0
sum = 0
for i,j in fish_records.items():
    print(i+'钓鱼记录为:')
    for x,y in j.items():
        print('\t{}数量{},单价{:.2f}元'.format(x,y[0],y[1]))
        n = n + y[0] 
        sum = sum + y[0] * y[1]
print('钓鱼总数量为{},总金额为{:.2f}元'.format(n,sum))

3.8 三酷猫钓鱼分类统计

在这里插入图片描述

dir_date1 = {'三酷猫': {'鲫鱼': [17, 10.5],'鲤鱼': [8, 6.2],'鲢鱼': [7, 4.7]},
             '加菲猫': {'黑鱼': [8, 16]},
             '大脸猫': {'草鱼': [12, 8]}}
dir_date2 = {'三酷猫': {'草鱼': [2, 7.2],'鲫鱼': [3, 12],'黑鱼': [6, 15]},
             '加菲猫': {'鲤鱼': [9, 7.1]}}
dir_date3 = {'三酷猫': {'乌龟': [1, 78.10],'鲫鱼': [1, 10.78],'草鱼': [5, 7.92]},
             '大脸猫': {'鲫鱼': [8, 9.8],'螃蟹': [5, 15]}}
fish_records = {'1月1日': dir_date1,'1月2日': dir_date2,'1月3日': dir_date3}
 
# 钓鱼总数量
total_nums = 0
# 钓鱼总金额
total_amount = 0
# 三酷猫的统计结果
three_cool_cat_statistics = {}
 
for day, day_record in fish_records.items():
    # 三酷猫当天钓鱼数量
    day_nums = 0
    # 三酷猫当天钓鱼金额
    day_amount = 0
    # 三酷猫当天每种鱼的数量和金额
    daily_fish_statistics = {}
 
    if '三酷猫' in day_record:
        three_cool_cat_record = day_record['三酷猫']
        for fish, fish_record in three_cool_cat_record.items():
            # 统计每种鱼的数量和金额
            if fish in daily_fish_statistics:
                daily_fish_statistics[fish][0] += fish_record[0]
                daily_fish_statistics[fish][1] += fish_record[0] * fish_record[1]
            else:
                daily_fish_statistics[fish] = [fish_record[0], fish_record[0] * fish_record[1]]
 
            # 统计三酷猫当天钓鱼总数量和总金额
            day_nums += fish_record[0]
            day_amount += fish_record[0] * fish_record[1]
 
            # 统计三天总的钓鱼数量和金额
            total_nums += fish_record[0]
            total_amount += fish_record[0] * fish_record[1]
 
    # 保存三酷猫每天的统计结果
    three_cool_cat_statistics[day] = {'数量': day_nums, '金额': day_amount, '鱼类统计': daily_fish_statistics}
 
print('=========每日钓鱼记录==========')
for day, stats in three_cool_cat_statistics.items():
    # print(f'{day}钓鱼数量为{stats["数量"]}, 金额为{stats["金额"]}')
    # print('鱼类统计:')
    print(f'{day}钓鱼记录为:')
    for fish, fish_stats in stats['鱼类统计'].items():
        print(f'\t{fish}数量{fish_stats[0]},单价{fish_stats[1] / fish_stats[0]:.2f}元')
 
# 按鱼进行数量,金额统计
# 相同的鱼归为一类
# 合并每种鱼的统计结果
merged_fish_statistics = {}
 
for day, stats in three_cool_cat_statistics.items():
    for fish, fish_stats in stats['鱼类统计'].items():
        # 如果已经存在的鱼类只需要计算数量、金额
        if fish in merged_fish_statistics:
            # 计算每种鱼的总数量
            merged_fish_statistics[fish][0] += fish_stats[0]
            # 计算每种鱼的总金额
            merged_fish_statistics[fish][1] += fish_stats[1]
        # 不存在的鱼要添加
        else:
            merged_fish_statistics[fish] = [fish_stats[0], fish_stats[1]]
 
print('=====按鱼进行数量,金额统计=====')
for fish, fish_stats in merged_fish_statistics.items():
    print(f'{fish}的总数量{fish_stats[0]},金额为{fish_stats[1]:.2f}元')
 
# 最大值,总数量,总金额统计
print('====最大值,总数量,总金额统计====')
max_fish_nums = max(merged_fish_statistics, key=lambda x: merged_fish_statistics[x][0])
max_fish_money = max(merged_fish_statistics, key=lambda y: merged_fish_statistics[y][1])
print(f'最大数量的鱼是{max_fish_nums},{merged_fish_statistics[max_fish_nums][0]}条')
print(f'最大金额的鱼是{max_fish_money},{merged_fish_statistics[max_fish_money][1]}元')
print(f'钓鱼总数量为{total_nums},总金额为{total_amount:.2f}元')
 

3.9 钓鱼内容字典修改

在这里插入图片描述

##print('=========每日钓鱼记录==========')
date1 = {'鲫鱼':[18,10.5],'鲤鱼':[8,6.2],'鲢鱼':[7,4.7]}
date2 = {'草鱼':[2,7.2],'鲫鱼':[3,12],'黑鱼':[6,15]}
date3 = {'乌龟':[1,71],'鲫鱼':[1,9.8],'草鱼':[5,7.2],'黄鱼':[2,40]}
records = {'1月1日':date1,'1月2日':date2,'1月3日':date3}
date1['鲫鱼'][0] = date1['鲫鱼'][0] - 1
for i in date3.values():
    i[1] = i[1] * 1.1
n1,n2,n3,n4,n5,n6 = 0,0,0,0,0,0
s1,s2,s3,s4,s5,s6 = 0,0,0,0,0,0
n = 0
s = 0
for x, y in records.items():
    print('{}钓鱼记录为:'.format(x))
    if '黄鱼' in y.keys():
        y.pop('黄鱼')
    for j, k in y.items():           
        print('    {}数量{},单价{:.2f}元'.format(j,k[0],k[1]))
        n += k[0]
        s += k[0] * k[1]
print('钓鱼总数量为{},总金额为{:.2f}元'.format(n,s))

3.10 复杂钓鱼账本

在这里插入图片描述

d_date1={'三酷猫':{'鲫鱼':[17,10.5],'鲤鱼':[8,6.2],'鲢鱼':[7,4.7]},'加菲猫':{'黑鱼':[8,16]},'大脸猫':{'草鱼':[12,8]}}     #1月1日钓鱼记录
d_date2={'三酷猫':{'草鱼':[2,7.2],'鲫鱼':[3,12],'黑鱼':[6,15]},'加菲猫':{'鲤鱼':[9,7.1]}}         #1月2日钓鱼记录
d_date3={'三酷猫':{'乌龟':[1,78.10],'鲫鱼':[1,10.78],'草鱼':[5,7.92]},'大脸猫':{'鲫鱼':[8,9.8],'螃蟹':[5,15]}}        #1月3日钓鱼记录
fish_records={'1月1日':d_date1,'1月2日':d_date2,'1月3日':d_date3}  #所有钓鱼记录 
nums=0          #钓鱼总数量初始化定义
amount=0        #钓鱼总金额初始化定义
day=''          #日期记录变量初始化定义

#==============================================按鱼名进行数量,金额累计
print('=========每日钓鱼记录==========')
for day,day_record in fish_records.items():    #循环获取每天记录(元组形式)
    if nums>0:
        print('-----------------')
    day_nums=0      #每天钓鱼数量
    day_amount=0    #每天钓鱼金额
    print('%s钓鱼记录为:'%(day))               #打印当天的日期
    for name1,get_fish_record1_d in day_record.items(): #循环获取当天钓鱼记录
        print('   %s:'%(name1))                     #打印钓鱼者
        for name2,get_fish_record2_d in get_fish_record1_d.items():    #获取鱼名和对应值(列表)
            day_nums+=get_fish_record2_d[0]                            #当天数量累加
            day_amount+=get_fish_record2_d[0]*get_fish_record2_d[1]    #当天金额累加
            print('      %s数量%d,单价%.2f元'%(name2,get_fish_record2_d[0],get_fish_record2_d[1]))#打印名称,数量,单价
    print('%s,钓鱼数量为%d,金额为%.2f元'%(day,day_nums,day_amount))    #打印当天钓鱼数量、金额
    nums+=day_nums                                                     #所有数量累加
    amount+=day_amount                                                 #所有金额累加
print('========统计结果打印=========')
print('钓鱼总数量为%d,总金额为%.2f元'%(nums,amount)) #打印总数量,总金额

4.1 定制手机套餐

call = ["0分钟","50分钟","100分钟","300分钟","不限量"]
liu = ["0M","500M","1G","5G","不限量"]
message = ["0条","50条","100条"]
print("定制自己的手机套餐:")
#A.通话时长的选择
print("A.请设置通话时长:")
for i,j in enumerate(call):
    print(str(i+1) + "." + j)
print("输入选择的通话时间编号:3")
#B.流量的选择
print("\nB.请设置流量:")
for i,j in enumerate(liu):
    print(str(i+1) + "." + j)
print("输入选择的通话时间编号:4")
#C.短信的选择
print("\nC.请设置短信条数:")
for i,j in enumerate(message):
    print(str(i+1) + "." + j)
print("输入选择的通话时间编号:1")
#输出套餐结果
print("\n您的手机套餐定制成功:"
      + "免费通话时长为" + call[2] + "/月 ,"
      + "流量为" + liu[3] + "/月,"
      + "短信条数" + message[0] + "/月")

4.2 定制手机套餐(check())

def display(options):
    for i, option in enumerate(options):
        print(str(i+1) + '.' + option)

def check(choice, options):
    if choice < 1 or choice > len(options):
        return False
    return True

print("定制自己的手机套餐:")
call = ["0分钟", "50分钟", "100分钟", "300分钟", "不限量"]
flow = ["0M", "500M", "1G", "5G", "不限量"]
message = ["0条", "50条", "100条"]

# 通话时长
print("A.请设置通话时长:")
display(call)
A = int(input("输入选择的通话时长编号:"))
while not check(A, call):
    print("无效的选择,请重新输入:")
    A = int(input("输入选择的通话时长编号:"))

# 流量
print("\nB.请设置流量包:")
display(flow)
B = int(input("输入选择的流量包编号:"))
while not check(B, flow):
    print("无效的选择,请重新输入:")
    B = int(input("输入选择的流量包编号:"))

# 短信
print("\nC.请设置短信条数:")
display(message)
C = int(input("输入选择的短信条数编号:"))
while not check(C, message):
    print("无效的选择,请重新输入:")
    C = int(input("输入选择的短信条数编号:"))

# 套餐结果
print("\n您的手机套餐定制成功:"+ "免费通话时长为" + call[A-1] +
      "/月,"+ "流量为" + flow[B-1] + "/月,"+
      "短信条数" + message[C-1] + "/月")

4.2 补充

请添加图片描述

L=[1,1]
n=int(input())
for i in range(2,n):
    L.append(L[i-1]+L[i-2])
print(L[-1])

在这里插入图片描述

term,total = 1,1
while True:
    #n = int(input("请输入一个小于10的正整数 n: "))
    n=int(input())
    if(n==0): # 输入0,退出
        print('退出!')
        break
    if 0 < n < 10:
        for i in range(2,n+1):
            term=10*term+i
            #print(term)
            total+=term
        print(total)
        break
    else:
        print("请输入一个小于10的正整数.")

在这里插入图片描述

L=[1,2]
sign = -1
total_sum = 1.0
n=int(input())
for i in range(2,n):
    L.append(L[i-1]+L[i-2])
    
for i in range(1,n):
    term = sign * i/ L[i]
    total_sum += term
    sign *= -1
print("{:.6f}".format(total_sum))

4.3 定义函数

def function_tips():
    import datetime
    weekdays=['星期一','星期二','星期三','星期四','星期五','星期六','星期天']
    words=['含泪',
          '含泪播种',
          '含泪播种的人',
          '含泪播种的人一定',
          '含泪播种的人一定能笑',
          '含泪播种的人一定能笑着收获',
          '含泪播种的人一定能笑着收获快乐',]
    today=datetime.date.today()
    weekday=today.weekday()
    #weekday_name=weekdays[weekday]
    print('今天是',weekdays[weekday])
    print(words[weekday])

def fun_bmi(name,height,weight):
    name=str(name)
    height=eval(height)
    weight=eval(weight)
    bmi=weight/(height**2)
    print('%s的身高:%.2f米\t体重:%.2f千克'%(name,height,weight))
    print('%s的BMI的指数为:%.6f'%(name,bmi))
    if 0<bmi<18.5:
        print('你的体重过轻 @_@\n')
    elif 18.5<bmi<24:
        print('正常范围,注意保持(-_-)\n')
    else:
        print('过重,请注意健康\n')
fun_bmi('张三','1.83','60')


def fun_bmi3(*person):
    for list_person in person:
        for item in list_person:            
            name=item[0]
            height=item[1]
            weight=item[2]
            bmi=weight/(height**2)
            print('\n'+'='*13,name,'='*13)
            print('身高:%.2f米\t体重:%.2f千克'%(height,weight))
            print('BMI的指数为:%.6f'%(bmi))
            if 0<bmi<18.5:
                print('你的体重过轻 @_@')
            elif 18.5<bmi<24:
                print('正常范围,注意保持(-_-)')
            else:
                print('过重,请注意健康')
l1=[('张三',1.83,60),('李四',1.2,65.1)]
l2=[('李四',1.2,65.1),('张三',1.83,60)]
fun_bmi3(l1,l2)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值