set intersection问题求解(python版)

本文介绍了一种求两个升序排列的整数列表交集的方法,并提供了两种Python实现方案。第一种方案利用了Python内置的set方法进行交集运算;第二种方案则通过双指针技巧来提高效率。

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

Description:

You are given two sorted list of numbers(ascending order). The lists themselves are comma delimited and the two lists are semicolon delimited. Print out the intersection of these two sets.

Input sample:

File containing two lists of ascending order sorted integers, comma delimited, one per line. e.g. 

1,2,3,4;4,5,6
7,8,9;8,9,10,11,12

Output sample:

Print out the ascending order sorted intersection of the two lists, one per line
e.g.

4
8,9

方案一:

#使用python的list自带的函数intersection

import sys

if __name__ == "__main__":
    argv = sys.argv
    inf = open(argv[1],'r')
    while True:
        line = inf.readline()
        if len(line) == 0:
            break
        ll = line.split(';')
        s1 = ll[0].split(',')
        s2 = ll[1].split(',')
        rl = list(set(s2).intersection(set(s1)))
        print ','.join(rl)

方案二:

import sys

if __name__ == "__main__":

    argv = sys.argv
    inf = open(argv[1],'r')
    while True:
        line = inf.readline()
        if len(line) == 0:
            break
        ll = line.split(';')
        s1 = ll[0].split(',')
        s2 = ll[1].split(',')
        i = 0
        j = 0
        rl = []
        while i < len(s1) and j < len(s2):
            print i,s1[i]
            print j,s2[j]
            if int(s1[i]) == int(s2[j]):
                rl.append(s1[i])
                i += 1
                j += 1
            elif int(s1[i]) < int(s2[j]):
                i += 1
            else:
                j += 1
        print ','.join(rl)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值