我正在尝试从my For循环和if循环中获取结果。我想要的两个结果是supply=demand时的最优价格和最优产品。
def supply(p):
"""
This function calculates the supply of the video game as a function of price
:param P: Ideal price of the game
:return: The result of the calculated supply
"""
supply = 500 + 90 * p
return supply
def demand(p):
"""
This function calculates the demand as a function of price
:param P: Ideal price of the game
:return: the result of the calculated demand
"""
demand = 10000 - 35 * p
return demand
for p in range(10 , 161, 1):
demand_result = supply(p)
supply_result = demand(p)
print('Price is:', p , 'Demand # is:' , demand_result , 'Supply # is:' , supply_result)
if demand_result == supply_result:
p = optimal_price
supply_result = optimal_product
print('The optimal price is ${:.2f}'.format(optimal_price))预期结果是价格=76.00美元,产品= 7340
发布于 2019-10-03 01:51:07
您可以将每个元素保存到一个列表中,然后将此列表保存到一个json文件中,以便下次需要时加载数据。
# importing the library that is necessary to deal with json files.
import json
# opens a json file that exist in the current directory, the file is readable only.
file = open("some_file.json", "r")
''' opens a json file that exist in the current directory, and if not, will create one, if the file already exists,
writing in it will overwrite what was already written in the file.'''
file_1 = open("some_file_1.json", "w")
''' opens a json file that exist in the current directory, and if not, will create one, if the file already exists,
writing in it will not overwrite what was already written in the file, writing in it will append the new data.'''
file_2 = open("some_file_2.json", "a")
# writes into an already opened json file, doesn't work in mode "r" (readable), overwrites in "w" and appends in "a".
json.dump(new_data, file_1)
# returns json objects that exist in the file as dictionaries, works only on files that are opened with mode "r" (readable).
json.load(file)
# closes the file after we finish using it.
file.close()发布于 2019-10-03 02:24:54
以下代码提供了所需的输出(最大限度地减少对原始代码的更改)
def supply(p):
"""
This function calculates the supply of the video game as a function of price
:param P: Ideal price of the game
:return: The result of the calculated supply
"""
supply = 500 + 90 * p
return supply
def demand(p):
"""
This function calculates the demand as a function of price
:param P: Ideal price of the game
:return: the result of the calculated demand
"""
demand = 10000 - 35 * p
return demand
for p in range(10 , 161, 1):
demand_result = demand(p) # compute demand & supply
supply_result = supply(p)
#print('Price is:', p , 'Demand # is:' , demand_result, 'Supply # is:' , supply_result)
if demand_result == supply_result: # demand meets supply
optimal_price = p
optimal_supply = supply_result
break # break for loop since we're found match
print('The optimal price is ${:.2f}'.format(optimal_price))
print('The optimal supply is {:.2f}'.format(optimal_supply))输出
The optimal price is $76.00
The optimal supply is 7340.00https://stackoverflow.com/questions/58206737
复制相似问题