Skip to content

Instantly share code, notes, and snippets.

@gugu
Created December 19, 2017 04:56
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save gugu/541b350445f99e2b27a5d72bc9c7eb4b to your computer and use it in GitHub Desktop.
Save gugu/541b350445f99e2b27a5d72bc9c7eb4b to your computer and use it in GitHub Desktop.
# Возвращаем элементы первого массива, которые есть во втором
import random
import time
def intersection_with_loops(first_array, second_array):
result = []
for first_element in first_array:
if first_element in second_array:
result.append(first_element)
return result
def intersection_with_dicts(first_array, second_array):
result = []
second_dict = {k: True for k in second_array}
for first_element in first_array:
if first_element in second_dict:
result.append(first_element)
return result
first_array = [random.randint(0, 100000) for _ in range(50000)]
second_array = [random.randint(0, 100000) for _ in range(50000)]
start_time = time.time()
intersection_with_loops(first_array, second_array)
first_completed_time = time.time()
print("Loop in loop completed in %.f seconds" % (first_completed_time - start_time))
intersection_with_dicts(first_array, second_array)
second_completed_time = time.time()
print("Dict + loop completed in %.f seconds" % (second_completed_time - first_completed_time))
# Loop in loop completed in 32 seconds
# Dict + loop completed in 0 seconds
@CrazyLionHeart
Copy link

start_time = time.time()
set(first_array).intersection(set(second_array))
first_completed_time = time.time()
print("Loop in loop completed in %.f seconds" % (first_completed_time - start_time))
Loop in loop completed in 0 seconds

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment