TheAlgorithms-Python
90 строк · 2.4 Кб
1"""
2Given an array of integers and another integer target,
3we are required to find a triplet from the array such that it's sum is equal to
4the target.
5"""
6
7from __future__ import annotations
8
9from itertools import permutations
10from random import randint
11from timeit import repeat
12
13
14def make_dataset() -> tuple[list[int], int]:
15arr = [randint(-1000, 1000) for i in range(10)]
16r = randint(-5000, 5000)
17return (arr, r)
18
19
20dataset = make_dataset()
21
22
23def triplet_sum1(arr: list[int], target: int) -> tuple[int, ...]:
24"""
25Returns a triplet in the array with sum equal to target,
26else (0, 0, 0).
27>>> triplet_sum1([13, 29, 7, 23, 5], 35)
28(5, 7, 23)
29>>> triplet_sum1([37, 9, 19, 50, 44], 65)
30(9, 19, 37)
31>>> arr = [6, 47, 27, 1, 15]
32>>> target = 11
33>>> triplet_sum1(arr, target)
34(0, 0, 0)
35"""
36for triplet in permutations(arr, 3):
37if sum(triplet) == target:
38return tuple(sorted(triplet))
39return (0, 0, 0)
40
41
42def triplet_sum2(arr: list[int], target: int) -> tuple[int, int, int]:
43"""
44Returns a triplet in the array with sum equal to target,
45else (0, 0, 0).
46>>> triplet_sum2([13, 29, 7, 23, 5], 35)
47(5, 7, 23)
48>>> triplet_sum2([37, 9, 19, 50, 44], 65)
49(9, 19, 37)
50>>> arr = [6, 47, 27, 1, 15]
51>>> target = 11
52>>> triplet_sum2(arr, target)
53(0, 0, 0)
54"""
55arr.sort()
56n = len(arr)
57for i in range(n - 1):
58left, right = i + 1, n - 1
59while left < right:
60if arr[i] + arr[left] + arr[right] == target:
61return (arr[i], arr[left], arr[right])
62elif arr[i] + arr[left] + arr[right] < target:
63left += 1
64elif arr[i] + arr[left] + arr[right] > target:
65right -= 1
66return (0, 0, 0)
67
68
69def solution_times() -> tuple[float, float]:
70setup_code = """
71from __main__ import dataset, triplet_sum1, triplet_sum2
72"""
73test_code1 = """
74triplet_sum1(*dataset)
75"""
76test_code2 = """
77triplet_sum2(*dataset)
78"""
79times1 = repeat(setup=setup_code, stmt=test_code1, repeat=5, number=10000)
80times2 = repeat(setup=setup_code, stmt=test_code2, repeat=5, number=10000)
81return (min(times1), min(times2))
82
83
84if __name__ == "__main__":
85from doctest import testmod
86
87testmod()
88times = solution_times()
89print(f"The time for naive implementation is {times[0]}.")
90print(f"The time for optimized implementation is {times[1]}.")
91