在 Python 中查找是否有可能从给定的成本和数量范围获得比率

pythonserver side programmingprogramming更新于 2025/10/10 9:48:17

假设我们有一个从 lowCost 到 upCost 的成本范围和另一个从 lowQuant 到 upQuant 的数量范围,我们必须检查是否可以找到给定的比率 r,其中 r=cost/quantity,并且 lowCost ⇐ cost ⇐ upCost 和 lowQuant ⇐ 数量 ⇐ upQuant。

因此,如果输入为 lowCost = 2、upCost = 10、lowQuant = 3、upQuant = 9 和 r = 3,则输出将为 True,因为 cost = r * quantity = 3 * 3 = 9,其中 cost 在范围 [1, 10] 内,数量在 [2, 8] 内

为了解决这个问题,我们将遵循以下步骤 −

  • 对于 i 在 l_quant 到 u_quant 范围内,执行

    • res := i * ratio

    • 如果 l_cost ⇐ res and res ⇐ u_cost,然后

      • 返回 True

  • 返回 False

示例

让我们看看下面的实现以便更好地理解 −

def can_we_find_r(l_cost, u_cost, l_quant, u_quant, ratio) :
   for i in range(l_quant, u_quant + 1) :
      res = i * ratio
      if (l_cost <= res and res <= u_cost) :
         return True
   return False

l_cost = 2
u_cost = 10
l_quant = 3
u_quant = 9
ratio = 3

print(can_we_find_r(l_cost, u_cost,l_quant,u_quant, ratio))

输入

2, 10, 3, 9, 3

输出

True

相关文章


有用资源