Reputation: 257
def profit():
price = input('Enter a price: ')
demand = 650 - (10 * price)
cost_per_item = 35
firm_profit = (price - cost_per_item) * demand
return firm_profit
How can one search through a range of prices to find the price that provides the highest profit based on this relationship between demand and the product?
Upvotes: 3
Views: 654
Reputation: 25023
Another possibility: first define a demand
function, next a profit
function and eventually use the max
builtin applied to a generator expression that produces couples of values (profit, price)
that max
, by default, compares taking into account the first value in the couple.
>>> def demand_01(price):
... return 650-10*price
>>> def profit(price, cost, demand):
... return (price-cost)*demand(price)
>>> print(max((profit(price, 35, demand_01), price) for price in (39.95, 69.90, 99.00))
(1239.9750000000008, 39.95)
The advantage of definining separately a demand
and a profit
function and using max
lies in
profit
function anddemand
functions to explore the sensitivity of the results on different assumptions.Addendum
To have the best price and the associated maximum profit you can unpack the result returned by the max
builtin:
max_profit, best_price = max( (profit(price, 35, demand_01), price)
for price in (...))
Upvotes: 1
Reputation: 8378
It is really a mathematical problem. Your formula for profit is:
profit = (p - c) * d = (p - c) * (650 - 10 * p)
where I abbreviated p
for price
, c
for cost_per_item
, d
for demand
.
To maximize profit
all that you need to do is to find the value of p
for which derivative of profit
with regard to p
is zero:
d(profit) / d(p) = 650 + 10*c - 20*p = 0 =>
pmax = (650 + 10*c) / 20
If you need to pick a price from a list of possible values, pick the one closest to pmax
(since profit
is a parabola with regard to p
and so it is symmetric around the vertical line passing through pmax
).
Therefore, if you do have a list of prices (I suppose this is what you mean by "range of values") contained in a list prices
, then:
best_price = min(abs(x - pmax) for x in prices)
where pmax
was computed earlier.
Upvotes: 1
Reputation: 26
If this problem uses discreet units (for example, if you must use integers) then you just use a loop to try every possibility from a price of 0 to a price which would produce a zero demand (65 in this case, because 650 - 10*65 = 0).
I would start by moving the price from an input to a parameter of the function, so:
def profit(price):
demand = 650 - (10 * price)
cost_per_item = 35
firm_profit = (price - cost_per_item) * demand
return firm_profit
Then we define a variable to pass through the function and increment it to try every possibility:
price = 0
best_price = 0
increment = 1
while price<65:
if profit(price)>profit(best_price):
best_price = price
price += increment
If you end up needing to use a decimal increment, you might want to use the decimal module to avoid some strange, floating point behavior.
Upvotes: 0