Skip to content

Instantly share code, notes, and snippets.

@gunlinux
Forked from gugu/slow.py
Created December 21, 2017 02:25
Show Gist options
  • Select an option

  • Save gunlinux/c2f38f3c9f2733ca789992c455881780 to your computer and use it in GitHub Desktop.

Select an option

Save gunlinux/c2f38f3c9f2733ca789992c455881780 to your computer and use it in GitHub Desktop.

Revisions

  1. @gugu gugu created this gist Dec 19, 2017.
    31 changes: 31 additions & 0 deletions slow.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,31 @@
    # Возвращаем элементы первого массива, которые есть во втором
    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