首页 > 解决方案 > 元素类型组合的解决方案,当任何类型都可以有零个元素时

问题描述

我有 3 个模型/实体,A、B、C(后端是 django)。

在前端我有 3 个空框,我需要在其中添加 A、B、C 的实例。A、B、C 的可用实例数可以是 0 到无限。

理想情况下,我应该显示 A 的 1 个、B 的 1 个和 C 的 1 个,但有时任何实体都可以没有实例。可以是无、一个或多个,没有实例。

我的基本方法是使用ifs,但效率不高,请仅查看伪代码中的一个分支:

if not C:
   if A:
      if not B:
         show up to 3 of A if they are available
      elif B:
        if at least 2 of A:
          show 2 of A and 1 Of B
        if 1 of A:
          show 1 of A and up to 2 of B
   elif not A:
      show up to 3 of B if exist  

除了ifs在所有分支上都有几十个之外,它不会扩展,例如,如果我将来添加一个新的实体和/或框。

所以,我正在寻找一种可以扩展的算法。我正在使用 Python、django、PostgreSQL。我提取数据,简单:

A.objects.all().order_by('-id')[:3]

标签: pythondjangopython-3.x

解决方案


models = [A, B, C]
num_boxes = len(models)  # but could be different
objects = [list(model.objects.all().order_by('-id')[:num_boxes])
           for model in models]
boxes = []

while any(objects):
    for row in objects:
        if row:
            boxes.append(row.pop(0))

print(sorted(
    boxes[:num_boxes],
    key=lambda x: models.index(type(x))
))

推荐阅读