set intersection问题求解(python版)

来源:互联网 发布:电信4g是什么网络模式 编辑:程序博客网 时间:2024/05/29 19:53

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,67,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.

48,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)
原创粉丝点击