algorithm - 如何跟踪 a/a + b?

标签 algorithm dictionary

我想随着时间的推移跟踪 a/(a+b) 的比率。 a 和 b 的值随时间增加。增量存储在字典中,其中键代表离散时间。示例:

a = {1:1, 15:1, 17:2, 21:1, ..}
b = {1:1, 4:1, 13:2, 22:1, ..}

输出应该是

ratio = {1:1/2, 4:1/3, 13:1/5, 15:2/6, 17:4/11, 21:5/9, 22:5/10, ..} 

对于根据ab 计算ratio,您有什么建议?

最佳答案

这是一个非常标准的基于事件的模拟模式。您需要将输入映射转换为“事件”,按发生时间对它们进行排序,然后按时间顺序处理它们以跟踪分子和分母。当排序的时间发生跳跃时,就该发出输出值了。最后一个细节是,如果在数据耗尽时有一个“等待”尚未发生的跳转,则确保发出最终值。像这样:

def track(a, b):
  # Events are triples: (a/b, time, value).
  events = map(
      lambda item: ('a', item[0], item[1]), a.items()) + map(
      lambda item: ('b', item[0], item[1]), b.items())
  events.sort(key = lambda item: item[1])
  num = 0
  den = 0
  t = events[1][1]
  result = {}
  for event in events:
    t_new = event[1]
    # If the previous time step has ended, emit its fraction.
    if t_new != t:
      result[t] = str(num) + '/' + str(den)
      t = t_new
    # Update the fraction.
    den += event[2]
    if event[0] == 'a':
      num += event[2]
  # Emit the final time step.
  if t not in result:
    result[t] = str(num) + '/' + str(den)
  return result

a = {1:1, 15:1, 17:2, 21:1};
b = {1:1, 4:1, 13:2, 22:1};

print track(a, b)


然后……

$ python foo.py
{1: '1/2', 4: '1/3', 13: '1/5', 15: '2/6', 17: '4/8', 21: '5/9', 22: '5/10'}

关于algorithm - 如何跟踪 a/a + b?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58332100/

相关文章:

java - 开源词典库

Python:如何修改字典列表中的特定(键,值)对?

java - 在遗传算法中,应该使用什么交叉方法来交叉 Postfix 表达式?

c# - 二叉搜索树遍历 - PreOrder

C++: bool 值的二进制表示是否有任何保证?

scala - 使用循环在 Scala 中创建 map

string - 使用动态规划对字符串进行分割

c++ - 为什么非递归方法比递归方法花费更多时间?

java - 用 Java Python 遍历 map ?

python - 我可以相信 dict 的顺序在每次迭代时都保持不变吗?