Advertisement
Guest User

Untitled

a guest
Feb 17th, 2020
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.51 KB | None | 0 0
  1. def bf_find_closest_triplet(sample, target):
  2.     res = 10000000
  3.     triplet = []
  4.     for i in range(len(sample)):
  5.         for j in range(len(sample)):
  6.             for k in range(len(sample)):
  7.                 if i != j and i != k and j != k:
  8.                     s = sample[i] + sample[j] + sample[k]
  9.                     if abs(s-target) < res:
  10.                         res = abs(s-target)
  11.                         triplet = [sample[i], sample[j], sample[k]]
  12.     return res, triplet
  13.  
  14. def find_closest_triplet(sample, target):
  15.     d = Counter(sample)
  16.     merge_sort(sample)
  17.     i = 0
  18.     j = len(sample)-1
  19.     while i < j:
  20.         s = sample[i] + sample[j]
  21.         d[sample[i]] -= 1
  22.         d[sample[j]] -= 1
  23.         third_num = target - s
  24.         print(sample[i], sample[j], "difference =",s, "third_num = ", third_num)
  25.         if third_num in d and d[third_num] > 0:
  26.             return [sample[i], sample[j], third_num]
  27.         else:
  28.             d[sample[i]] += 1
  29.             d[sample[j]] += 1
  30.             if third_num < 0:
  31.                 j -= 1
  32.             else:
  33.                 i += 1
  34.  
  35. for _ in range(100):
  36.     n = rand.randrange(0, 20)
  37.     sample = [rand.randrange(-20, 20) for _ in range(n)]
  38.     target = rand.randrange(-50, 50)
  39.     res, triplet = bf_find_closest_triplet(sample, target)
  40.     if res == 0:
  41.         print("Sample = ", sample)
  42.         print("Target = ", target)
  43.         print("Brute force:", triplet)
  44.         print("My solution:", find_closest_triplet(sample, target))
  45.         print()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement