Home > Enterprise >  Find the intersection of two sorted lists of integers using sys in Python 3
Find the intersection of two sorted lists of integers using sys in Python 3

Time:11-04

If you have done HireVue coding challenges you know that you have inputs that are already in the system and should be called with:

import sys (I guess)

How should I write the code that reads raw inputs to find the intersection between the 2 lists?

An intersection is simply a common value between the 2 lists.

My attempt:

def intersection(lst1, lst2):
    lst3 = [value for value in lst1 if value in lst2]
    return lst3

The problem is that I don't know how to put in the code the command that reads the raw input.

CodePudding user response:

Just use the intersection operator of a set:

def intersection(lst1, lst2):
    return list(set(lst1) & set(lst2))

CodePudding user response:

If you have import sys and you need to take inputs as well on your own, one way that I am aware of is using sys.stdin for input.

sys.stdin is the Standard Input Stream for Python that normally uses the terminal or console running the program for input. But it can be updated to use some different file as well. It might be the case that your code platform has updated this parameter to reference their own input.

With sys.stdin, you have methods that can help you in taking inputs from stdin such as:

  • sys.stdin.read(): To read some characters from sys.stdin
  • sys.stdin.readline(): To read a line from sys.stdin
  • sys.stdin.readlines(): To read multiple lines from sys.stdin

To check about all its available methods, use import sys; help(sys.stdin) with Python 3.

Now, for your required code for intersection, [val for val in lst1 if val in lst2] might work as expected, but will take some more time since in operator in lists will look for your val in lst2 in O(n) time, which can be optimised if you use sets, as mentioned in other answers here.

I hope it helps. I was initially planning to leave a comment, but with under 50 reputation for now, I had no other choice but to separately answer to your question. Let me know by commenting below if anything is incorrect or unclear here and we might update it.

  • Related