这个函数的目标是计算股票的买入和卖出。由于某种原因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
1条答案
按热度按时间7xzttuei1#
错误是你试图将像
"buy 20 shares at 24 each"
这样的字符串拆分成3个变量。该拆分有6个项目,因此出现too many values to unpack (expected 3)
错误消息。要修复它,只需拆分事务,然后提取您关心的字段:如果你做了这样的修改,那么你的代码几乎可以工作了,但是你试图在
shares[0] -= shares_sold
行中改变一个元组。要解决这个问题,请将shares_bought
重新定义为列表的双端队列,而不是元组的双端队列: