Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Find if it is possible to get a ratio from given ranges of costs and quantities in Python
Suppose we have a range of cost from lowCost to upCost and another range of quantity from lowQuant to upQuant. We need to check whether we can find the given ratio r where r = cost/quantity, with lowCost ? cost ? upCost and lowQuant ? quantity ? upQuant.
So, if the input is like lowCost = 2, upCost = 10, lowQuant = 3, upQuant = 9 and r = 3, then the output will be True as the cost = r * quantity = 3 * 3 = 9 where cost is in range [2, 10] and quantity is in [3, 9].
Algorithm
To solve this problem, we will follow these steps ?
- For each quantity
iin range [lowQuant, upQuant], calculatecost = i * ratio - If the calculated cost falls within [lowCost, upCost], return True
- If no valid combination is found, return False
Example
Let us see the following implementation to get better understanding ?
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))
True
How It Works
The function iterates through each possible quantity value from 3 to 9. For each quantity, it calculates the corresponding cost using cost = quantity * ratio. When quantity = 3, cost = 3 × 3 = 9, which falls within the cost range [2, 10], so the function returns True.
Alternative Approach Using Mathematical Range
We can also solve this more efficiently by calculating the valid cost range directly ?
def can_we_find_r_optimized(l_cost, u_cost, l_quant, u_quant, ratio):
# Calculate the range of possible costs
min_cost = l_quant * ratio
max_cost = u_quant * ratio
# Check if the cost ranges overlap
return not (max_cost < l_cost or min_cost > u_cost)
l_cost = 2
u_cost = 10
l_quant = 3
u_quant = 9
ratio = 3
print(can_we_find_r_optimized(l_cost, u_cost, l_quant, u_quant, ratio))
True
Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Iterative | O(n) | O(1) | Small ranges |
| Mathematical | O(1) | O(1) | Large ranges |
Conclusion
Both approaches determine if a given ratio can be achieved within specified cost and quantity ranges. The iterative method is straightforward but less efficient for large ranges, while the mathematical approach provides constant-time solution by checking range overlap.
