Я хочу кумулятивно добавить элемент на Arraystack в Pythonстек Python перекрывающийся элемент кумуляции
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 в 'buy_shares'? –
Кроме того, зачем использовать стек? Почему не словарь? –
Ах, поскольку он предназначен для использования данных strucutre - stack, поэтому я создал и использовал стек, а не словарь. Я также считаю, что словарь намного эффективнее. –