下面的代码解决了这个问题,但我不确定它是最快或最干净的方法。如果代码速度有任何改进,我将不胜感激。
from __future__ import division
Z = {1: 0.5, 2: 1.5, 3: 2.0, 4: 0.02, 5: 3.1}
total = sum(Z.values())
lb = 1 / (10 * len(Z.keys()))
print lb, "lower bound"
U = []
for k in Z.keys():
if Z[k] > lb:
U.append(k)
B = []
for k in Z.keys():
if Z[k] <= lb:
U.append(k)
def setBound():
count = 0
for k in U:
w = Z[k]
if w < lb:
Z[k] = lb
U.remove(k)
B.append(k)
count += 1
return count
def normalize():
bounded_sum = lb * len(B)
unbounded_sum = 0
for k in U:
unbounded_sum += Z[k]
multiple = (1-bounded_sum) / unbounded_sum
for k in U:
Z[k] *= multiple
def adjust():
normalize()
count = setBound()
if count > 0:
normalize()
return adjust()
else:
return
adjust()
print Z
print sum(Z.values()), "sum of all values"