gpt4 book ai didi

python列表似乎随机消失

转载 作者:行者123 更新时间:2023-12-01 04:03:48 26 4
gpt4 key购买 nike

我制作了一个脚本来测试我编写的不同排序算法的运行时间。代码在这里:

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)

最佳答案

您的函数 sort.selection 正在修改传入的列表,如下所示:

ints.remove(maxint)

如果您想操作列表的本地副本,请添加:

ints = ints[:]

sort.selection() 例程的早期。

关于python列表似乎随机消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36016675/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com