我将两个整数设置为彼此相等,但我仍然得到:'int'对象不可下标?



我是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
但我不断得到:

回溯(最近一次调用(: 第 32 行,在 get_max_profit(stock_prices( 第 20 行,get_max_profit 如果stock_prices[i] == 买入: 类型错误:"int"对象不可下标

你能检查这一行吗:

for stock_prices in stock_prices

并将其替换为

for stock_price in stock_prices

它将解决您的问题,

但我确实认为你的逻辑也有问题,所以你不会得到预期的结果。

这是改进的逻辑,但我建议您先自己尝试一下,这必须是最后的手段:

stock_prices = [12, 7, 5, 8, 11, 14]
buy = min(stock_prices)
sell = max(stock_prices)

def get_max_profit(stock_prices):
    i = 0
    j = 1
    for stock_price 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[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:
            i = i + 1
            j = j + 1

def app():
    get_max_profit(stock_prices)

if __name__ == '__main__':
    app()

快乐编码

最新更新