【问题标题】:pythonic way to fix index out of range in sliding windowpythonic方法来修复滑动窗口中超出范围的索引
【发布时间】:2021-03-22 21:57:59
【问题描述】:

我正在使用滑动窗口做这个 leetcode 问题,我意识到我得到了 IndexError,因为可以得到的最大值 j (= idx+1) 超出了范围。我想知道是否有一种优雅的方法来解决它?

链接:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/

问题陈述:

You are given an array prices where prices[i] is the price of a given stock on the ith day. Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).

输入输出示例:

Input: prices = [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.

这是我的代码:

class Solution:
def maxProfit(self, prices: List[int]) -> int:
   
    totalProfit = 0
    currentProfit = 0
    
    for idx, x in enumerate(prices):
      
        j = idx+1
        
        while prices[j] > prices[idx] and prices[j] > prices[j-1]:
            
            currentProfit = prices[j] - prices[idx]
            totalProfit += currentProfit
            
            j += 1
 
    return totalProfit

错误信息:

IndexError: list index out of range
while prices[j] > prices[idx] and prices[j] > prices[j-1]:

编辑:正如@Prune 所建议的,当 j 在进入下一次迭代之前超出边界时,我会中断循环。它适用于示例输入,但我没有用极端情况测试它。让我们讨论一下是否还有改进的余地!

这是更新后的代码:

class Solution:
def maxProfit(self, prices: List[int]) -> int:
   
    totalProfit = 0
    currentProfit = 0
    
    for idx, x in enumerate(prices): 
      
        j = idx+1
        
        if j == len(prices): # boundary: break before entering loop
            break
        
        elif prices[j] > prices[idx] and prices[j] > prices[j-1]: # when continue to increase, enter loop

            currentProfit = prices[j] - prices[idx] # return value
            totalProfit += currentProfit # sum and return
      
            j += 1 #increase window size
            
    return totalProfit

【问题讨论】:

  • 请提供预期的minimal, reproducible example (MRE)。我们应该能够复制并粘贴您的代码的连续块,执行该文件,并重现您的问题以及跟踪问题点的输出。这让我们可以根据您的测试数据和所需的输出来测试我们的建议。
  • 一般来说,解决这个问题的优雅方法是在进入循环之前计算正确的边界;仅在合法范围内进行迭代。这是基本代数;你到底卡在哪里了?由于您未能提供完整的错误消息和正确的跟踪,我们必须正确检测和运行您的代码以获取所需的信息。这是你的任务。
  • 你不需要一个类,一个简单的函数就足够了,因为你在这段代码中没有任何状态。您是 Java 开发人员吗?

标签: python loops indexing


【解决方案1】:

这是你需要的吗?

from typing import List

def max_profit(prices: List[int]) -> int:
    profit = 0
    if len(prices) > 1: 
        bought_at = prices[0]
        for price in prices[1:]: 
            if bought_at and bought_at < price:
                print(f'sell at: {price} - bought at : {bought_at}')
                profit += (price - bought_at)
                bought_at = 0
            else:
                bought_at = price
    return profit     

result = max_profit([7,1,5,3,6,4])
print(f'profit: {result}')

输出:

$ python3 so.py
sell at: 5 - bought at : 1
sell at: 6 - bought at : 3
profit: 7

【讨论】:

  • 有趣的解决方案!我用不同的输入 [1,2,3,4,5] 尝试了它,但它返回了 2,而预期的答案是 4。
  • Tbh 我不确定我们应该在什么时候买卖;-)
  • 我觉得就是会持续涨价,最后一天卖出,跌了再买
猜你喜欢
  • 1970-01-01
  • 2021-01-27
  • 1970-01-01
  • 1970-01-01
  • 2013-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多