Skip to content

Instantly share code, notes, and snippets.

@folt
Created April 22, 2022 20:51
Show Gist options
  • Save folt/8c62561ae3ce9d1e001763ce8793813d to your computer and use it in GitHub Desktop.
Save folt/8c62561ae3ce9d1e001763ce8793813d to your computer and use it in GitHub Desktop.
one-s
import typing
from time import time
from profile import profile
def timer(func):
def wrap_func(*args, **kwargs):
stat = time()
result = func(*args, **kwargs)
end = time()
print(f'Time: {(end - stat):.8f}s')
return result
return wrap_func
def get_list(n: int) -> typing.List[int]:
return [item for item in range(n)]
@timer
def my_func_1(n: int, x: int) -> None:
result1 = []
my_list1 = get_list(n)
for a in my_list1:
for b in my_list1:
if a + b > x:
continue
if a == b:
continue
if (a, b) in result1:
continue
if (b, a) in result1:
continue
result1.append((a, b))
print(f'Result: {result1}')
print(f'Count: {len(result1)}')
@timer
def my_func_2(n: int, x: int) -> None:
# тут был взят set, потому что первом варианте на самом деле нет грантии,
# что список будет содержать уникальные элементы
result2 = set()
my_list2 = get_list(n)
for a in my_list2:
for b in my_list2:
if a + b > x:
continue
if a == b:
continue
# поскольку пара (1 2) и (2 1) эквиволентны по условию, значит можно
# эти значения отсортировать и построить ключ который будет
# характеризировать эту пару
my_kye = f'{a}-{b}' if a > b else f'{b}-{a}'
# так же еще один бонус от использования set-а, это быстрая проверка
# на нахождения ключа в set-е, поскольку он построен на хеш таблице
if my_kye in result2:
continue
result2.add(my_kye)
print(f'Result: {result2}')
print(f'Count: {len(result2)}')
my_func_1(n=10000, x=10)
print('================')
my_func_2(n=10000, x=10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment