python - Return tuple of any two items in list, which if summed equal given int -


for example, assume given list of ints:

int_list = list(range(-10,10)) [-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 

what efficient way find if given 2 values in int_list sum equal given int, 2?

i asked in technical phone interview morning on how efficiently handle scenario int_list of say, 100 million items (i rambled , had no answer :/).

my first idea was:

from itertools import combinations int_list = list(range(-10,10)) combo_list = list(combinations(int_list, 2)) desired_int = 4 filtered_tuples = list(filter(lambda x: sum(x) == desired_int, combo_list)) filtered_tuples [(-5, 9), (-4, 8), (-3, 7), (-2, 6), (-1, 5), (0, 4), (1, 3)] 

which doesn't work range of range(-10000, 10000)

also, know of online python performance testing tool?

for integer a there @ 1 integer b sum equal integer n. seems easier go through list, arithmetic, , membership test see if b in set.

int_list = set(range(-500000, 500000)) target_num = 2  def filter_tuples(int_list, target):     int_ in int_list:         other_num = target - int_         if other_num in int_list:             yield (int_, other_num)  filtered_tuples = filter_tuples(int_list, target_num) 

note duplicate results. e.g. (-2, 4) separate response (4, -2). can fix changing function:

def filter_tuples(int_list, target):     int_ in int_list:         other_num = target - int_         if other_num in int_list:             set.remove(int_)             set.remove(other_num)             yield (int_, other_num) 

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -