Skip to content

Commit 88fcde4

Browse files
committed
Create DistanceMetric.py
1 parent eaab699 commit 88fcde4

1 file changed

Lines changed: 38 additions & 0 deletions

File tree

01_base/练习/DistanceMetric.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# Python3 program for the above approach
2+
from collections import defaultdict
3+
4+
# Function to find sum of differences
5+
# of indices of occurrences of each
6+
# unique array element
7+
def sum_i(arr, n):
8+
# Stores indices of each array element
9+
mp = defaultdict(lambda : [])
10+
# Store the indices
11+
for i in range(n):
12+
mp[arr[i]].append(i)
13+
# Stores the sums
14+
ans = [0] * n
15+
16+
# Traverse the array
17+
for i in range(n):
18+
# Find sum for each element
19+
sum = 0
20+
# Iterate over the Map
21+
for it in mp[arr[i]]:
22+
# Calculate sum of occurrences of arr[i]
23+
sum += abs(it - i)
24+
# Store sum for current element
25+
ans[i] = sum
26+
# Print answer for each element
27+
for i in range(n):
28+
print(ans[i], end = " ")
29+
30+
# Driver code
31+
if __name__ == '__main__':
32+
# Given array
33+
arr = [ 1, 3, 1, 1, 2 ]
34+
# Given size
35+
n = len(arr)
36+
# Function Call
37+
sum_i(arr, n)
38+
# This code is contributed by Shivam Singh

0 commit comments

Comments
 (0)