2016-02-03 47 views
0

我必須推動棧中的一些20000項來檢查時間複雜度。 這裏是我的代碼randint函數沒有迭代列表

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

重複,看到這個問題http://stackoverflow.com/questions/35045392/using-產量在-A-功能/ 35045413#35045413 –

回答

0

random.randint(1,2000)返回一個不可迭代的int值,用range和xrange來迭代它。

for i in xrange(random.randint(1,2000)) #use range in python3.x 
1

,如果你只是想填充大量數據的堆棧可以使用

for i in range(200000): 
    stack.push(i) 

,而不是你的循環,但這樣會在連續填充200000號堆,如果你想隨機他們,你可以添加此

import random 
    random.sample(range(30), 200000) 

其中範圍(30)是數字將是從1到30和200000的項目

,然後你可以使用循環來推動他們在上面

0

如已經顯示堆棧試試這個

for i in range(random.randint(1,2000)): 
    stack.push(i) 
    end_time=time()