• API
• FAQ
• Tools
• Archive
SHARE
TWEET

# minimal distance between elements on list

furas Jul 25th, 2018 (edited) 66 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. import numpy as np
2.
3. # --- version 1 ---
4.
5. def np_min_distance(data, val1, val2):
6.     pos1 = np.where(data == val1)
7.     pos2 = np.where(data == val2)
8.
9.     dist = 0
10.
11.     for x in pos1[0]:
12.         for y in pos2[0]:
13.             d = abs(x-y)
14.             if dist == 0 or d < dist:
15.                 dist = d
16.
17.     return dist
18.
19.
20. data = np.array([1, 5, 3, 7, 2, 8, 3, 4, 5, 9, 9, 3, 1, 3, 2, 9])
21.
22. print( '4, 7 -> 4', np_min_distance(data, 4, 7) == 4 )
23. print('---')
24.
25. print( '9, 3 -> 1', np_min_distance(data, 9, 3) == 1 )
26. print('---')
27.
28. data = np.array([4, 4, 4, 4, 7, 7, 7, 7, 4, 4])
29.
30. print( '4, 7 -> 1', np_min_distance(data, 4, 7) == 1 )
31. print('---')
32.
33.
34. print('------------------------------------------------')
35.
36. # --- version 2 ---
37.
38. def min_distance(data, val1, val2):
39.     pos1 = None
40.     pos2 = None
41.     dist = 0 # or some big value
42.     previous = None
43.
44.     for pos, item in enumerate(data):
45.
46.         if item == val1:
47.             pos1 = pos
48.             if pos1 and pos2 and previous != val1: # if `pos1` and `post2` is not `None` then `previous` can't be `None` so I don't have to check if `previous is not None`
49.                 d = abs(pos1 - pos2)
50.                 print('pos:', pos1, pos2, '->', d)
51.                 if dist == 0 or d < dist:
52.                     dist = d
53.                 #if dist == 1:
54.                 #    return 1
55.             previous = val1
56.
57.         elif item == val2:
58.             pos2 = pos
59.             if pos1 and pos2 and previous != val2:
60.                 d = abs(pos1 - pos2)
61.                 print('pos:', pos1, pos2, '->', d)
62.                 if dist == 0 or d < dist:
63.                     dist = d
64.                 #if dist == 1:
65.                 #    return 1
66.             previous = val2
67.
68.     #print('result:', dist)
69.
70.     return dist # zero means no found
71.
72.
73. data = [1, 5, 3, 7, 2, 8, 3, 4, 5, 9, 9, 3, 1, 3, 2, 9]
74.
75. print( '4, 7 -> 4', min_distance(data, 4, 7) == 4 )
76. print('---')
77.
78. print( '9, 3 -> 1', min_distance(data, 9, 3) == 1 )
79. print('---')
80.
81. data = [4, 4, 4, 4, 7, 7, 7, 7, 4, 4]
82.
83. print( '4, 7 -> 1', min_distance(data, 4, 7) == 1 )
84. print('---')
85.
86. print( '9, 3 -> 0', min_distance(data, 9, 3) == 0 )
87. print('---')
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy.

Top