代码:
class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def length(stack):
i = 0
while not stack.is_empty():
stack.pop()
i += 1
return i
s1 = Stack()
s1.push(3)
s1.push(2)
s1.push(1)
print(length(s1))
s1.pop()
输出:
3
Traceback (most recent call last):
File "Stack.py", line 26, in <module>
s1.pop()
File "Stack.py", line 12, in pop
return self.items.pop()
IndexError: pop from empty list
我希望函数length()
能够修改s1
的副本,而不是更改s1
。有没有办法在python中做到这一点?
我不允许直接使用s1.items
,因此我无法使用s1[:]
。我也无法修改课程。
答案 0 :(得分:2)
您只需使用copy
模块:
import copy
# ... your code ...
print(length(copy.deepcopy(s1))) # pass a copy to the length function
或者如果你想要它没有额外的模块,如果你可以改变length
功能,你可以简单地保留pop
ped项目和push
它们的长度:< / p>
def length(stack):
i = 0
tmp = []
while not stack.is_empty():
tmp.append(stack.pop()) # append them to your temporary storage
i += 1
for item in tmp: # take the items saved in the temporary list
stack.push(item) # and push them into your stack again
return i