python-3.x 我需要帮助调试事务,split方法

tvokkenx  于 2023-10-21  发布在  Python
关注(0)|答案(1)|浏览(126)

这个函数的目标是计算股票的买入和卖出。由于某种原因transaction.split方法返回错误。错误是说这个方法需要3个参数,我有。在这方面的任何帮助是非常感谢!

from collections import deque

def calculate_gain(stock_transactions):
    gain = 0
    shares_bought = deque()

    for transaction in stock_transactions:
        action, num_shares, share_price = transaction.split()
        num_shares = int(num_shares)
        share_price = int(share_price)

        if action == 'buy':
            shares_bought.append((num_shares, share_price))
        else:
            shares_sold = num_shares

    while shares_sold > 0:
        shares = shares_bought.popleft()
        if shares[0] > shares_sold:
            gain += shares_sold * (share_price - shares[1])
            shares[0] -= shares_sold
            shares_bought.appendleft(shares)
            shares_sold = 0
        else:
            gain += shares[0] * (share_price - shares[1])
            shares_sold -= shares[0]

    return gain

    stock_transactions = [
    "buy 100 shares at 20 each",
    "buy 20 shares at 24 each",
    "buy 200 shares at 36 each",
    "sell 150 shares at 30 each"
    ]

    total_gain = calculate_gain(stock_transactions)
    print(f"The total capital gain is ${total_gain}")

我试着改变参数的名称、间距和缩进。它仍然没有正确拆分。
Error Image

7xzttuei

7xzttuei1#

错误是你试图将像"buy 20 shares at 24 each"这样的字符串拆分成3个变量。该拆分有6个项目,因此出现too many values to unpack (expected 3)错误消息。要修复它,只需拆分事务,然后提取您关心的字段:

transaction = transaction.split()
action = transaction[0]
num_shares = int(transaction[1])
share_price = int(transaction[4])

如果你做了这样的修改,那么你的代码几乎可以工作了,但是你试图在shares[0] -= shares_sold行中改变一个元组。要解决这个问题,请将shares_bought重新定义为列表的双端队列,而不是元组的双端队列:

shares_bought.append([num_shares, share_price])

相关问题