【发布时间】:2019-06-12 03:10:57
【问题描述】:
我是 Python 新手,正在尝试一些基本问题来帮助我学习和练习基础知识。问题来了:
给定股票价格列表(每日)。考虑到列表中股票价格的顺序,返回最佳利润。 (卖出价已在列表中买入价之后)代码如下:
stock_prices = [12, 7, 5, 8, 11, 14]
i = 0
j = 1
buy = min(stock_prices)
sell = max(stock_prices)
def get_max_profit(stock_prices):
for stock_prices in stock_prices:
if stock_prices[i] == buy:
return print("Buy Price:", stock_prices[i], "Sell Price:", max(stock_prices[i:]),
"Profit:", max(stock_prices[i:]) - stock_prices[i])
elif stock_prices[i] > stock_prices[j]:
return i + 1, j + 1
elif stock_prices[j] > stock_prices[i] and (stock_prices[i:] != buy and stock_prices[i:] > stock_prices[i]):
return print("Buy Price:", stock_prices[i], "Sell Price:", max(stock_prices[i:]),
"Profit:", max(stock_prices[i:]) - stock_prices[i])
else:
return i + 1, j + 1
get_max_profit(stock_prices)
我希望得到:
“买入价:” 5 “卖出价:” 14 “利润:” 9
但我不断得到:
Traceback(最近一次调用最后一次): 第 32 行,在 获得最大利润(股票价格) 第 20 行,在 get_max_profit 如果 stock_prices[i] == 购买: TypeError: 'int' 对象不可下标
【问题讨论】:
-
您能否再看看您的程序的语法 --
return print...不是有效的 Python -
即使在返回后删除打印,我仍然得到同样的错误
-
我没有看到与您完全相同的错误,但我确实看到使用与您的数组相同的循环变量名称可能存在问题 --
for stock_prices in stock_prices -
@DanielCorin
return print(...)应该是有效的。函数会返回None,返回值print。 -
@Tomothy32 你是对的。我最近在 python 2 和 3 之间切换太多了
标签: python