我編寫了一個腳本來測試我編寫的不同排序算法的運行時間。該代碼是在這裏:python list貌似隨機消失
import random
import sort
import time
print ('test sort functions for integer lists')
integers = [random.randint(1,999) for n in range(1, random.randint(1000,2000)) ]
print('ordering', len(integers), 'ints')
print('start selection sort')
ts=time.clock()
print(sort.selection(integers))
print ('end selection sort with time', time.clock()-ts, '\n')
print('start merge sort')
tm=time.clock()
print(sort.merge(integers))
print ('end merge sort with time', time.clock()-tm, '\n')
當調用函數sort.merge(integers)
,空單傳遞給它的某些原因。我通過在那裏放置print(integers)
來測試這個,但據我所知應該與傳遞給sort.selection(integers)
的完全一樣。有人知道發生了什麼事嗎?我sort.py模塊的
內容:
import math
def merge(ints):
if (len(ints) < 2):
return (ints)
else:
print('recursion')
i=merge(ints[0:math.ceil(len(ints)/2)]) #calls recursive function for
j=merge(ints[math.ceil(len(ints)/2):]) #both halves of list
k=[] #beginning of merge algorithm
ic=0
jc=0
while (ic < len(i) and jc < len(j)): #repeat as long as end of i
if (i[ic] < j[jc]): #append lowest value to k
k.append(i[ic])
ic+=1 #track which values of i are accounted for
if (ic == len(i)): #if i is exhausted
for a in range (jc, len(j)): #fill k with j
k.append(j[jc])
jc+=1
break
if (i[ic] >= j[jc]):
k.append(j[jc])
jc+=1
if (jc == len(j)):
for a in range (ic, len(i)):
k.append(i[ic])
ic+=1
break
return (k)
def selection(ints,order='a'):
maxint=0
orderedints=[]
if (order == 'desc' or order == 'descending' or order == 'd'):
while (len(ints) > 0):
maxint=maxof(ints)
ints.remove(maxint)
orderedints.append(maxint)
return (orderedints)
if (order == 'asc' or order == 'ascending' or order == 'a'):
while (len(ints) > 0):
minint=maxof(ints)
for i in range (0, len(ints)):
if (ints[i] < minint):
minint = ints[i]
ints.remove(minint)
orderedints.append(minint)
return (orderedints)
def maxof(a):
maxint=0
for i in range (0, len(a)):
if (a[i] > maxint):
maxint = a[i]
return (maxint)
所以,當我通過列表的功能,它並沒有複製該名單,只是與同時引用列表工作? – murtaza64
是的,這是正確的。 –