较长较难代码集锦(不断更新)

m = max(x)
index = [index for index,value in enumerate(x) if value == m]
#编写程序,生成20个随机数的列表,
#然后将前10个元素升序排列,后10个元素降序排列,并输出结果。
from random import randint
a = [randint(1,100) for i in range(20)]
print(a)
b = a[:10]
c = a[10:]
b = sorted(b,reverse = True)
c = sorted(c,reverse = False)
print(b)
print(c)
a = b + c
print(a)
#统计字符出现的频率(字典最基本操作)
import random
import string
x = string.ascii_letters + string.digits
z = ''.join((random.choice(x) for i in range(1000)))
d = dict()
for ch in z:
    d[ch] = d.get(ch,0) + 1
for k,v in sorted(d.items()):
    print(k,':',v)

二分法查找元素重要

#二分法查找元素(适用于有序的列表查找)
alist = [1,2,3,4,5,6,7,8,12,15,18,19,20]
low = 0
high = len(alist) - 1
s = int(input("请输入要查找的元素:"))
while low <= high:
    mid = (low + high) // 2
    if alist[mid] < s:
       low = mid + 1
    elif alist[mid] > s:
         high = mid - 1
    else:
        print("The number {}index  in {} is {}".format(s,alist,mid));
        break;
else:
    print("No found of {}".format(s))
#出现最大值的下标
scores = {"Zhang San":45,"Li Si":78,"Wang Wu":99,"Zhou Liu":96,
          "Zhao Qi":65,"Sun Ba":90,"Zheng Jiu":78,"Wu Shi":99,
          "Dong Shi yi":60}
m = max(scores.values())
highestPerson = [name for name,score in scores.items() if score == m]
print(highestPerson)
"""
根据十年高考录取率表创建列表,并完成如下操作: 
① 计算十年平均录取率。 
② 找出录取率最高的年份。 
"""
rate_dict = {2006:57,2007:56,2008:57,2009:62,2010:69,
             2011:72,2012:75,2013:76,2014:74.3,2015:74}
rate_dictNew = dict(zip(rate_dict.values(),rate_dict.items()))
rate_average = sum(rate_dict.values()) / (len(rate_dict.items()))
m = max(rate_dict.values())
#year = rate_dictNew.get(m,"NONE!!!")
#year = rate_dictNew[m]               这种方法最简洁。有特殊要求的选其余两种,是再加还是返回错误值
year = rate_dictNew.setdefault(m,'aoligei')
print('The average rate of it is {}'.format(rate_average))
print("The year of the highest rate is {}".format(year))

"""
用字典统计英文句子“Life is short, we need Python.”
中各字符出现的次数(大小写算同一个字符)。
"""
sentense = 'Life is short, we need Python'
rate = {}
for alphabet in sentense:
    rate[alphabet] = rate.get(alphabet,0) + 1
print(rate)
"""
小夏和小迪接到一个调研任务,需要按省份统计班级同学的籍贯分布情况。
他们决定两人分头统计男生和女生的籍贯分布,最后再汇总结果。
已知小夏统计的女生籍贯分布是:
dicGirls={'Jiangsu':3,'Zhejiang':2,'Jilin':1} ;
小迪统计的男生籍贯分布是
:dicBoys={'Jiangsu':8,'Zhejiang':5,'Shandong':5,'Anhui':4,'Fujian':2}。
请编写程序将两人的调研结果合并并输出。
"""
dicGirls={'Jiangsu':3,'Zhejiang':2,'Jilin':1} 
dicBoys={'Jiangsu':8,'Zhejiang':5,'Shandong':5,'Anhui':4,'Fujian':2}
dic = dicBoys.copy()
for k,v in dicGirls.items():
    dic[k] = dic.get(k,0) + v
print(dic)
#课本P71:NB的算法:
from random import randrange
#其他用户喜欢的电影清单
data = {'user' + str(i):{'film'+str(randrange(1,10))\
                         for j in range(randrange(15))}\
        for i in range(10)}
#待测用户曾经看过并觉得不错的电影
user = {'film1','film2','film3'}
similarUser,films = max(data.items(),\
                        key = lambda item:len(item[1]&user))
print('历史数据')
for u,f in data.items():
    print(u,f,sep = ':')
print('和您最相似的用户是:',similarUser)
print('他最爱的电影:',films)
print('他爱看的电影中你没有看过的是:',films-user)

#计算平均分自己写的,没有异常数据处理:
score = []
while True:
    score.append(int(input('请输入分数:')))
    answer = input('继续输入吗?(yes\no)')
    if answer =='yes':
        continue
    elif answer =='no':
        break
print('The average score is :',sum(score) / len(score))    
#课本正确写法:
score = []
while True:
    x = input('请输入成绩:')
    try:
        score.append(float(x))      #将可能出错的语句放在try里
    except:                         #如果不对,执行except语句
        print('不是合法数字!')
    while True:
        answer = input('继续输入吗?(yes \ no)')
        if answer.lower() not in('yes','no'):       #.lower()是转换成小写字母,输入YES、NO均可
            print('只能输入yes和no!')
        else:
            break
    if answer.lower() == 'no':
        break
print(sum(score) / len(score))
#编写程序,判断今天是今年的第几天
import time
date = time.localtime()         #获取当前的日期时间
print(date)
year,month,day = date[:3]       #切片 + 序列解包
day_month = [31,28,31,30,31,30,31,31,30,31,30,31]   #每个月有多少天
if year % 400 == 0 or(year % 4 == 0 and year % 100 != 0): #判断是否为闰年
    day_month[1] = 29
if month == 1:
    print(day)
else:
    print(sum(day_month[:month - 1]) + day)
#我觉得应该有的注释:++++分析
import time
date = time.localtime()         #获取当前的日期时间
print(date)
#year month day 分别代表今年,几月,几号
year,month,day = date[:3]       #切片 + 序列解包
day_month = [31,28,31,30,31,30,31,31,30,31,30,31]   #每个月有多少天
if year % 400 == 0 or(year % 4 == 0 and year % 100 != 0): #判断是否为闰年
    day_month[1] = 29           #闰年的二月有29天
if month == 1:                  #如果是当前时间是1月,直接输出要比sum效率更高
    print(day)
else:
    #求和,列表比月份少1。列表是左闭右开,所以还是不包含本月,再加上本月
    print(sum(day_month[:month - 1]) + day)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值