2012-09-22 25 views
1

我正在使用Bisect函數在python中編寫一個簡單的集合抽象。這裏的問題是,當我使用insort函數在列表中添加數據時,函數返回None。但是當我使用BISECT.BISECT(lst,ele)時,該函數返回值,如果需要,函數可以插入元素的列表的索引。使用insort(lst,ele)時函數不返回值

# Python program to implement collection abstraction 
# using Bisect Algorithm 
# The program would add an element into the SORTED LIST" 
# which would be the input 
# The program would test whether the element is in the collection 
# And also, to return the element of the collection if it is there 

from bisect import bisect 
from bisect import insort_right 

the_list = [] 

def add(lst,ele): 

    return insort_right(lst,ele) 

#def test(lst,ele) 

#def remove(lst,ele): 


print("Enter the size of the list:") 
N = int(input()) 

for x in range(N): 

    x = input("")  
    the_list.append(x) 
    the_list.sort() 

print(the_list) 

print("Enter the element to be added in the list") 
element = input("") 

add_element = add(the_list,element) 
print("The element is added in collection at location:", add_element) 
+0

爲什麼這是一個問題? – delnan

回答

1

insort,因爲它改變了列表本身沒有返回值。通常,這種使用副作用的Python函數不會返回值。如果你想從add返回修改後的列表,這樣做:

def add(lst, ele): 
    insort_right(lst, ele) 
    return lst 

但真的這樣做,因爲返回的列表是一樣的中傳遞列表中沒有點調用方面已經有了。訪問該列表,所以不需要返回它,這樣做有點單一。

+0

感謝您的建議。我正在通過一本名爲探索python的書,通過timothy budd學習python。有一個練習的問題陳述是使用Bisect函數實現集合抽象。它必須實現三個函數add(lst,ele)來將元素添加到集合中。同樣,如果元素在集合中,則測試(lst,ele)返回true;否則返回false。 – vamosrafa

+0

所以我認爲問題是以這樣的方式實現一個函數,即從命令行調用add(lst,ele)必須在排序列表中添加元素而不會破壞或違反列表的排序順序。 – vamosrafa

+1

這聽起來是對的。幸運的是,'insort'已經爲你做好了,所以解決方案就是在這裏建立的。 – senderle