day8集合作业

这篇博客探讨了Python编程中的集合操作,包括求选课学生的总数、只选一门或多门课程的学生数量及其名字。此外,还介绍了如何找出列表中出现次数最多的元素以及实现根据日期判断是今年第几天的程序。示例代码分别展示了如何处理这些场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. 用三个集合表示三门学科的选课学生姓名(一个学生可以同时选多门课)

    history = {'赛文','杰克','艾斯','雷欧','爱迪','戴拿'}
    art = {'初代','爱迪','泰罗','戴拿','泽塔','赛文'}
    music = {'泰罗','戴拿','泽塔','高斯','迪迦'}
    

    a. 求选课学生总共有多少人

    all_nums = history | art | music
    print(len(all_nums))
    

    b. 求只选了第一个学科的人的数量和对应的名字

    reslut = history - art - music
    print(len(reslut),reslut)
    

    c. 求只选了一门学科的学生的数量和对应的名字

    reslut = (history ^ art ^ music) - (history & art & music)
    print(len(reslut),reslut)
    

    d. 求只选了两门学科的学生的数量和对应的名字

    s5 =all_nums - reslut - (history & art & music)
    print(len(s5),s5)
    

    e. 求选了三门学生的学生的数量和对应的名字

    s3 = history & art & music
    print(len(s3),s3)
    
  2. 获取列表中出现次数最多的元素

    例如:nums = [1, 2, 3,1,4,2,1,3,7,3,3] —> 打印:3

    nums = [1,2,2,1,3] --> 打印1、2

    nums = [1,2,2,1,3]
    set1 = set(nums)
    # print(set1)
    max_times = 0
    num = []
    for i in set1:
        times = nums.count(i)
        # print(times)
        if times > max_times:
            max_times = times
    for i in set1:
        if nums.count(i) == max_times:
            num.append(i)
    print(num)
    # 方法2
    max_times = 0
     reslut = []
     for i in set1:
         count = nums.count(i)
         if count > max_times:
             max_times = count
             reslut.clear()
             reslut.append(i)
         elif count == max_times:
             reslut.append(i)
     print(max_times,reslut)
    
  3. 实现给定一个日期,判断这个日期是今年第几天的程序(尝试

    例如:2022/12/31 --> 今年第365天;2022/1/1 --> 今年第1天

    # 方法1
     import time
     date = '2022/12/31'
     s_date = time.strptime(date,'%Y/%m/%d')
     print(s_date.tm_yday)
     # 方法2
     year_ = int(input('输入年:'))
     month_ = int(input('输入月:'))
     day_ = int(input('输入日:'))
     month_day = {1:31, 2:28, 3:31, 4:30, 5:30, 6:31, 7:31, 8:31, 9:30, 10:31, 11:30, 12:31}
     if year_ % 400 == 0 or (year_ % 4 ==0 and year_ % 100 != 0):
         month_day[2] = 29
     
     total_day = day_
     for i in range(1,month_):
         total_day += month_day[i]
     print(total_day)
     
     
     # 方法3
     month_day = [31, 28, 31, 30, 30, 31, 31, 31, 30, 31, 30, 31]
     if year_ % 400 == 0 or (year_ % 4 ==0 and year_ % 100 != 0):
         month_day[1] = 29
     total_day = day_ + sum(month_day[:month_ - 1])
     print(total_day)
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值