Reputation: 11
I have to push some 20000 items in a stack to check the time complexity. Here's my code
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()
but its showing error as
for i in random.randint(1,2000):
TypeError: 'int' object is not iterable
and someone help me to get rid of this error please I want to analyze the time and space complexity and for less value the time is coming to be 0.0 so I want to test it on large numbers.
Upvotes: 0
Views: 80
Reputation: 1366
try this
for i in range(random.randint(1,2000)):
stack.push(i)
end_time=time()
Upvotes: 0
Reputation: 19
if you just want to populate your stack with large data you can use
for i in range(200000):
stack.push(i)
instead of your for loop but this will populate the stack with 200000 numbers from in continuation and if you want to randomize them you can add this
import random
random.sample(range(30), 200000)
where range(30) is that numbers will be from 1 to 30 and 200000 is for number of items
and then you can use for loop to push them in stack as already shown above
Upvotes: 1
Reputation: 3741
random.randint(1,2000) returns a int which is not iterable, use range and xrange to iterate on it.
for i in xrange(random.randint(1,2000)) #use range in python3.x
Upvotes: 0