gpt4 book ai didi

Python堆栈重叠元素累加

转载 作者:太空宇宙 更新时间:2023-11-03 15:48:32 26 4
gpt4 key购买 nike

我想在Python中的Arraystack上累积添加元素

class StockManager:

__PROFIT = 0

def __init__(self, o_name, o_surname):
self.box = ArrayStack()
self._name = o_name
self._surname = o_surname

def buy_shares(self, company, number, buy_price):
StockManager.__PROFIT -= buy_price * number
n = 0

if len(self.box) < 2:
"""there is no overlapped elements when box has no element"""
self.box.push(company)
self.box.push(number)
else:
while n < len(self.box):
if self.box._data[n] == company:
"""every even index(n = 0, 2, 4, ...) refers to company name"""
"""every odd index(n = 1, 3, 5, ...), which is next to even index refers to number of buying"""
self.box._data[n + 1] += number
n += 2

elif self.box._data[n] != company:
""" if there's no overlapping, then just put the elements """
self.box.push(company)
self.box.push(number)
n += 2
return print(self.box._data)

Arraystack 类是这样的:

class ArrayStack:
"""LIFO Stack implementation using a Python list as underlying storage."""

def __init__(self):
"""Create an empty stack."""
self._data = [] # nonpublic list instance

def __len__(self):
"""Return the number of elements in the stack."""
return len(self._data)

def is_empty(self):
"""Return True if the stack is empty."""
return len(self._data) == 0

def push(self, e):
"""Add element e to the top of the stack."""
self._data.append(e) # new item stored at end of list

def top(self):
"""Return (but do not remove) the element at the top of the stack.

Raise Empty exception if the stack is empty.
"""
if self.is_empty():
raise AssertionError('Stack is empty')
return self._data[-1] # the last item in the list

def pop(self):
"""Remove and return the element from the top of the stack (i.e., LIFO).

Raise Empty exception if the stack is empty.
"""
if self.is_empty():
raise AssertionError('Stack is empty')
return self._data.pop() # remove last item from list

def print_contents(self):
print("Stack content: {0}".format(self._data))

当我运行stockmanager时

if __name__ == '__main__':
P = StockManager("A","B")
P.buy_shares("hyundai", 20, 100)
P.buy_shares("hyundai", 20, 100)
P.buy_shares("hyundai", 20, 100)
P.buy_shares("lg", 20, 100)

结果是

['hyundai', 20]  => O.K
['hyundai', 40] => O.K
['hyundai', 60] => O.K
['hyundai', 60, 'lg', 40] => It should be ['hyundai', 60, 'lg', 20]
['hyundai', 60, 'lg', 60, 'lg', 40] => don't know why this result comes...

我该如何解决这个问题?

最佳答案

所以,问题出在你的while上循环:

           while n < len(self.box):
if self.box._data[n] == company:
"""every even index(n = 0, 2, 4, ...) refers to company name"""
"""every odd index(n = 1, 3, 5, ...), which is next to even index refers to number of buying"""
self.box._data[n + 1] += number
n += 2

elif self.box._data[n] != company:
""" if there's no overlapping, then just put the elements """
self.box.push(company)
self.box.push(number)
n += 2

想象一下我们已经跑了:

P = StockManager("A","B")
P.buy_shares("hyundai", 20, 100)
P.buy_shares("hyundai", 20, 100)
P.buy_shares("hyundai", 20, 100)

到目前为止,一切都按计划进行。现在,您尝试:

P.buy_shares("lg", 20, 100)

所以:n == 0len(self.box) == 2 ,所以我们进入循环。

if条件失败,self.box._data[n] != 'lg' ,所以我们转到 elif block :

           self.box.push(company)
self.box.push(number)
n += 2

现在,box == ['hyundai', 60, 'lg', 20]n == 2 。可是等等!循环条件为n < len(box) ,但是len(box) == 4 ,所以我们再次进入while循环!这次,if条件自 self.box._data[2] == 'lg' 起经过此时间.

因此,您执行 if block 的主体:

           self.box._data[n + 1] += number
n += 2

现在,n == 4box == ['hyundai', 60, 'lg', 40] 。这次,4 < len(box)失败,我们退出循环,您的函数也结束。

现在,堆栈对我来说似乎是错误的数据结构。必须将尺寸增加两倍,这很笨重。如果您真的想这样做,我建议采用类似的方法

offset = 0
i = -2
for i in range(0, len(self.box), 2):
if self.box._data[n] == company:
break
else:
offset = 2
self.box.push(company)
self.box.push(0)
self.box._data[i + offset + 1] += number

但是,这又很笨拙。您最好使用 dict对于盒子,那么逻辑可以简单地实现为:

self.box[company] = self.box.get(company, 0) + 1

或者更好的是,使用 defaultdict

>>> from collections import defaultdict
>>> box = defaultdict(int)
>>> box
defaultdict(<class 'int'>, {})
>>> box['lg'] += 20
>>> box
defaultdict(<class 'int'>, {'lg': 20})
>>> box['lg'] += 20
>>> box
defaultdict(<class 'int'>, {'lg': 40})
>>> box['lg']
40

关于Python堆栈重叠元素累加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41540864/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com