【问题标题】:I set two ints equal to each other but I still get: 'int' object is not subscriptable?我将两个整数设置为彼此相等,但我仍然得到:'int' 对象不可下标?
【发布时间】: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


【解决方案1】:

你能检查一下这一行吗:

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()

快乐编码

【讨论】:

  • 这确实有效。你对如何改进逻辑有什么建议吗?因为我没有得到任何输出
  • 谢谢@Perplexabot!我也是 stackoverflow 的新手。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-04
相关资源
最近更新 更多