Reputation: 552
Say I have a dictionary like so:
d = {1.0: 11, 2.0: 3, 3.0: 7}
I need to calculate the ratio of each value and the following value (k+1), then divide the sum of all ratios calculated by the number of ratios calculated, in this case, 2. If interested, this is for calculating a 'bifurcation ratio' in stream stats.
expected output:
sum of ratios = 3.67 + 0.43 = 4.1 solution = 4.1 / 2 = 2.05
Upvotes: 0
Views: 206
Reputation: 96
d = {1.0: 11, 2.0: 3, 3.0: 7}
d = list(d.values())
ratios = []
solution = 0.0
per = d[0]
for v in d[1:]:
ratios.append(per/v)
per = v
solution = sum(ratios)/len(ratios)
Upvotes: 2
Reputation: 474
d = {1.0: 11, 2.0: 3, 3.0: 7}
ratio_values = list(d.values())
count = len(ratio_values) - 1
ratio_sum = 0
for i in range(len(ratio_values) - 1):
#adds the ratio between two consecutive values to the total sum
ratio_sum += ratio_values[i]/ratio_values[i+1]
print(ratio_sum/count)
Upvotes: 2
Reputation: 921
import numpy as np
arr = np.array(list(d.values()))
arr
ans = 0
ratios = []
for i in range(1, len(arr)):
ratios.append(arr[i-1]/arr[i])
ans = sum(ratios)/len(ratios)
Upvotes: 2