我必须在堆栈中推送大约20000个项目以检查时间复杂度。 这是我的代码
from time import time
import random
class Node(object):
def __init__(self, value=None):
self.value = value
self.next = None
class StackwithNodes(object):
def __init__(self):
self.top = None
def isEmpty(self):
return bool(self.top)
def pop(self):
node = self.top
if node:
self.top = node.next
return node.value
else:
raise Exception('Stack is empty.')
def push(self, value):
node = Node(value)
node.next = self.top
self.top = node
def size(self):
node = self.top
num_nodes = 1
if node is None:
return 0
node = node.next
while node:
num_nodes =num_nodes+1
node = node.next
return num_nodes
def peek(self):
return self.top.value
def main():
stack = StackwithNodes()
start_time = time()
for i in random.randint(1,2000):
stack.push(i)
end_time=time()
end_time=time()
elapsed = end_time-start_time
print "the time for 100000 push operations with node is :",elapsed
print(stack.size())
print(stack.peek())
print(stack.pop())
print(stack.peek())
if __name__ == '__main__':
main()
但显示错误为
for i in random.randint(1,2000):
TypeError: 'int' object is not iterable
并且有人帮助我摆脱这个错误,我想分析时间和空间的复杂性,并且为了更少的价值,时间将变为0.0,所以我想在大数字上测试它。
答案 0 :(得分:1)
如果您只想使用大数据填充堆栈,可以使用
for i in range(200000):
stack.push(i)
而不是你的for循环但是这会在继续填充200000个数字的堆栈,如果你想随机化它们你可以添加这个
import random
random.sample(range(30), 200000)
其中范围(30)是数字从1到30,200000是项目数
然后你可以使用for循环将它们推入堆栈中,如上所示
答案 1 :(得分:0)
random.randint(1,2000)返回一个不可迭代的int,使用range和xrange迭代它。
for i in xrange(random.randint(1,2000)) #use range in python3.x
答案 2 :(得分:0)
试试这个
for i in range(random.randint(1,2000)):
stack.push(i)
end_time=time()