应用
现有M(1<=M<=10)个端口组,每个端口组是长度为N(1<=N<=100),元素均为整数。如果这些端口组间存在2个及以上的元素相同,则认为端口组可以关联合并;若可以关联合并,请用二位数组表示输出结果。其中,组内相同元素仅保留一个,从小到大排序;组外顺序保持输入顺序。
实现
M = int(input("请输入端口组个数M:"))
portgroups = []for i in range(0, M):pg = []string = input("请输入端口组的整数值,以空格分隔:").split() for j in string:pg.append(int(j))portgroups.append(pg)
# 二维数组
print(f"初始二维数组为:{portgroups}")def associate(list1, list2):same_element_num = 0for i in range(0, len(list1)):for j in range(0, len(list2)):if list1[i] == list2[j]:same_element_num += 1if same_element_num >= 2:# 合并、去重a = list(set(list1 + list2))# 排序b = sorted(a)# print(f"{list1}、{list2}相关联,结果为{b}")return b# else:# print(f"{list1}、{list2}不相关联")def integrate(portgroups):for i in range(0, len(portgroups)):for j in range(i+1, len(portgroups)):# 由于后面将个别列表置空了,所以增加判断,减少计算量if portgroups[i] and portgroups[j]:pg_associated = associate(portgroups[i], portgroups[j])if pg_associated:# 原二维数组的第i行列表被更换为关联列表portgroups[i] = pg_associated# 原二维数组的第j行列表更换为空列表portgroups[j] = []# 把整合后的、新的二维数组作为参数,再放进该函数里执行integrate(portgroups)# print(f"更改后的二维数组为:{portgroups}")new_portgroups = []for i in range(0, len(portgroups)):if portgroups[i]:new_portgroups.append(portgroups[i])return new_portgroupsprint(f"整合后的数组为:{integrate(portgroups)}")
请输入端口组个数M:6
请输入端口组的整数值,以空格分隔:10
请输入端口组的整数值,以空格分隔:4 2 1
请输入端口组的整数值,以空格分隔:9
请输入端口组的整数值,以空格分隔:3 6 9 2
请输入端口组的整数值,以空格分隔:6 3 4
请输入端口组的整数值,以空格分隔:8
初始二维数组为:[[10], [4, 2, 1], [9], [3, 6, 9, 2], [6, 3, 4], [8]]
整合后的数组为:[[10], [1, 2, 3, 4, 6, 9], [9], [8]]