python - IndexError:Python中的列表分配索引超出范围
问题描述
我正在尝试实现堆栈操作:
如果我尝试避免使用 .append() 并使用 self.size 进行索引并返回大小而不是使用 len(self.stack) 它会抛出这个:
Traceback (most recent call last):
File "C:\Users\user\Downloads\UPN.py", line 62, in <module>
print(round(test.upn(notation))
File "C:\Users\user\Downloads\UPN.py", line 50, in upn
self.push(float(el))
File "C:\Users\user\Downloads\UPN.py", line 16, in push
self.stack[self.size+1] = x
IndexError: list assignment index out of range
[]
Process finished with exit code 1
代码片段:
from time import sleep
class Stack:
def __init__(self):
self.stack = []
self.size = 0
self.operatoren = {
"+": (lambda a, b: a + b),
"-": (lambda a, b: a - b),
"*": (lambda a, b: a * b),
"/": (lambda a, b: a / b)
}
def push(self, x):
self.stack[self.size-1] = x
self.size += 1
def top(self):
return self.stack[self.size-1]
def pop(self):
self.size -= 1
return self.stack.pop()
def isEmpty(self):
return not self.stack
def size(self):
return self.size
def upn(self, expression):
elemente = expression.split()
for el in elemente:
print(self.stack)
if el not in self.operatoren:
self.push(float(el))
else:
zahl2 = self.pop()
zahl1 = self.pop()
ergebnis = self.operatoren[el](zahl1, zahl2)
self.push(ergebnis)
return self.pop()
test = Stack()
notation = "5.1 91 28 + 4.3 6 + * 777 + *"
print(round(test.upn(notation)))
解决方案
在“堆栈”类中:
class Stack:
...
def push(self, x):
self.stack[self.size-1] = x ##### target #####
self.size += 1
...
在目标行:
... self.size = 0 and self.stack[self.size-1] = x ->
... self.stack[0-1] = x
... self.stack[-1] = x
所以self.stack[self.size] = x
和:
class Stack:
...
def push(self, x):
self.stack[self.size] = x
self.size += 1
...
推荐阅读
- python - 可以在没有 GUI 的情况下完全使用 DaVinci Resolve python API 吗?
- ruby-on-rails - 切换到 structure.sql 后删除/保留 schema.rb
- swift - Swift 中未对齐的 UICollectionViewCells
- javascript - 使用ajax将照片和多个数据发送到控制器
- python - 在python中按文件名的一部分查找文件
- optimization - 如何最小化 Google OR-Tools 中的最大值?
- templates - 如何向现有问题数据集中的问题添加不同的短语?
- javascript - 如何使用 JavaScript querySelector() 编辑表格行?
- flutter - 在 webview_flutter 中导航时如何防止深度链接/单链接
- javascript - 需要帮助添加 playVideo();