python set小练习、编9
1.随机产生2组各个数字的列表,如下要求:
每个数字取值范围[10,20] 统计20个数字中,一共有多少个不同的数字?2组中,不重复的数字有几个?
分别是什么?2组中,重复的数字有几个?分别是什么?
1 import random 2 3 4 def panDuan_shuLiang(Set_One={1, 2}, Set_Two={2, 4}): 5 6 """该函数接受两个set,并返回两个set中所有元素的总数量""" 7 8 Set_zongYuanSu = len(Set_One) + len(Set_Two) 9 print("两个集合总共有 %d 个元素" % Set_zongYuanSu) 10 11 def panDuan_chongFu(Set_One={1, 2}, Set_Two={2, 4}): 12 13 """该函数接受两个set,并返回两个set的交集及其数量,不重复元素及其数量""" 14 15 # Set_jiaoJi返回set的交集 16 Set_jiaoJi = Set_One & Set_Two 17 18 # 将Set_jiaoJi的每个元素转化成str,并形成一个list 19 Set_jiaoJi_List = list(map(lambda x: str(x), Set_jiaoJi)) 20 print("重复的元素有 %d 个" % len(Set_jiaoJi_List)) 21 print("分别是 ", ",".join(Set_jiaoJi_List)) 22 23 # Set_bingJi返回set的并集 24 Set_bingJi = Set_One | Set_Two 25 26 # 用并集和交集之间的差集来求出两个set中不重合的元素 27 Set_buChongFu = Set_bingJi - Set_jiaoJi 28 # 将Set_buChongFu的每个元素转化成str,并形成一个list 29 Set_buChongFu_List = list(map(lambda x: str(x), Set_buChongFu)) 30 print("不重复的元素有 %d 个" % len(Set_buChongFu_List)) 31 print("分别是 ", ",".join(Set_buChongFu_List)) 32 33 def yuanSu(List_YuanSu_ShuLiang=10, List_fanWei=[10, 20]): 34 35 """该函数主要接受两个参数,分别是每个集合中的元素数量, 36 以及系统添加到集合中随机数的范围,范围以list的形式输入""" 37 38 List_A, List_B = [], [] 39 for i in range(List_YuanSu_ShuLiang): 40 List_A.append(random.randint(List_fanWei[0], List_fanWei[-1])) 41 List_B.append(random.randint(List_fanWei[0], List_fanWei[-1])) 42 List_A_Set = set(List_A) 43 List_B_Set = set(List_B) 44 45 print("list1:", List_A) 46 print("list2:", List_B) 47 print("集合1:", List_A_Set) 48 print("集合2:", List_B_Set) 49 50 panDuan_shuLiang(List_A_Set, List_B_Set) 51 panDuan_chongFu(List_A_Set, List_B_Set) 52 53 # 主程序 54 yuanSu()
2.编9:给你两个正整数a和b, 输出它们的最大公约数
1 ## 辗转相除法:取两个数中最大的数做除数,较小的数做被除数,用最大的数除较小数,如果余数为0,则较小数为这两个数的最大公约数, 2 ## 如果余数不为0,用较小数除上一步计算出的余数,直到余数为0,则这两个数的最大公约数为上一步的较小数。 3 4 # 两个数字最大值 5 def all_shuZi_max(shuZi_one=1, shuZi_two=2): 6 if shuZi_one > shuZi_two: 7 return shuZi_one 8 else: return shuZi_two 9 10 # 两个数字最小值 11 def all_shuZi_min(shuZi_one=1, shuZi_two=2): 12 if shuZi_one < shuZi_two: 13 return shuZi_one 14 else: return shuZi_two 15 16 # 求公约数 17 def gongYueShu(shuZi_one=1, shuZi_two=2): 18 shuZi_max = all_shuZi_max(shuZi_one, shuZi_two) 19 shuZi_min = all_shuZi_min(shuZi_one, shuZi_two) 20 shuZi_yuShu = shuZi_max % shuZi_min 21 if shuZi_yuShu == 0: 22 print(f"最大公约数为 {shuZi_min}") 23 else: 24 while 1: 25 shuZi_max = shuZi_min 26 shuZi_min = shuZi_yuShu 27 shuZi_yuShu = shuZi_max % shuZi_min 28 if shuZi_yuShu == 0: 29 print(f"最大公约数为 {shuZi_min}") 30 break 31 gongYueShu(1, 2)

浙公网安备 33010602011771号