实验3

task1.py

import random 

print('用列表存储随机整数: ')
ls = [random.randint(1, 100) for i in range(5)]
print(ls) 

print('\n用集合存储随机整数: ')
s1 = {random.randint(1,100) for i in range(5)} 
print(s1) 
 
print('\n用集合存储随机整数: ') 
s2 = set() 
while(len(s2)<5): 
    s2.add(random.randint(1,100)) 
print(s2)

问题1:范围是[1,100] ,能取到100

问题2:范围是[0,5),不包括5

             范围是[1,5),不包括5

问题3:不一定,因为randint可能取重复值,在集合中只显示一次

问题4:一定,因为是执行循环,所以结束的时候一定是5

task2.py

 

datas = {'2049777001': ['篮球', '羽毛球', '美食', '漫画'],
         '2049777002': ['音乐', '旅行'],
         '2049777003': ['马拉松', '健身', '游戏'],
         '2049777004': [],
         '2049777005': ['足球', '阅读'],
         '2049777006': ['发呆', '闲逛'],
         '2049777007': [],
         '2049777008': ['书法', '电影'],
         '2049777009': ['音乐', '阅读', '电影', '漫画'],
         '2049777010': ['数学', '推理', '音乐', '旅行']
         }
n = [x for i in datas.values() for x in i]
counts = [(n.count(x),x) for x in set(n)]
counts.sort(reverse=True)
for i in counts:
    print(f'{i[1]}:{i[0]}')

task3.py

temperatures= [['2022-04-18', '星期一', '10', '22'],
               ['2022-04-19', '星期二', '10', '22'],
               ['2022-04-20', '星期三', '12', '25'],
               ['2022-04-21', '星期四', '13', '28'],
               ['2022-04-22', '星期五', '16', '31'],
               ['2022-04-23', '星期六', '19', '31'],
               ['2022-04-24', '星期日', '19', '27']]
x = [int(i[2]) for i in temperatures]
y = [int(i[3]) for i in temperatures]
z = sum(x)//len(x)
t = sum(y)//len(y)
print(f'未来一周最低气温: {min(x)}℃')
print(f'未来一周最高气温: {max(y)}℃')
print(f'未来一周平均气温区间:{z}℃~{t}℃')

task4.py

import random
n = 0
t = [random.randint(1, 31) for i in range(1)]
print('猜猜2022年5月哪一天会是你的lucky day:-)')
x = int(input('你有三次机会,猜吧(1~31):  '))
while n < 2:
    if x == t[0]:
        print('哇,猜中了:-)')
        break
    elif x < t[0]:
        print('猜早啦,你的lucky day还没到呢')
        x = int(input('再猜(1~31): '))
    else:
        print('猜晚啦,你的lucky day已经过啦')
        x = int(input('再猜(1~31): '))
    n += 1
else:
    print('次数用光啦。')
    print(f'偷偷告诉你, 5月你的lucky day是{t[0]}号. good luck:-)')

 

task5.py

x,y = eval(input('输入十进制整数x和要转换的进制n(2或8或16): '))
X,Y = x,y
t = []
x1 = ["A","B","C","D","E","F"]
while x != 0:
    z = x % y
    if y == 16:
        if z > 9:
            w = z % 10
            z = x1[w]
    t.append(z)
    x = x//y
t.reverse()
t1 = ''.join(str(i) for i in t)
print(f'{X}的{Y}进制是:{t1}')

实验总结:

1.我学会了用列表或集合存储随机整数

2.对列表推导式的应用还不是很熟练

posted on 2022-04-23 12:53  好运来。  阅读(12)  评论(2编辑  收藏  举报