Python 中位数和时间
基本上,这里是应该返回中位数和时间的代码,但它在第32、30和6行显示了一个错误,“全局名称‘insertionSort’没有定义,我知道它没有定义,但我不知道如何实现它,以便它与此代码一起工作Python 中位数和时间,python,time,median,insertion-sort,Python,Time,Median,Insertion Sort,基本上,这里是应该返回中位数和时间的代码,但它在第32、30和6行显示了一个错误,“全局名称‘insertionSort’没有定义,我知道它没有定义,但我不知道如何实现它,以便它与此代码一起工作 import time start_time = 0 #starts the time from 0 seconds def median(lst): start_time = time.time() insertionSort(lst) if len(lst)%2==1:
import time
start_time = 0 #starts the time from 0 seconds
def median(lst):
start_time = time.time()
insertionSort(lst)
if len(lst)%2==1:
end_time = time.time()
print("Time: " , end_time - start_time) #prints the time of the process
return lst[len(lst)//2]
else:
return (lst[(len(lst)//2)-1]+lst[(len(lst)//2)//2])/2
def distSum(lst,n):
sum==0
for current in lst:
sum=sum+abs(current-bestLoc)
return sum
def main():
fileName = input('Enter a filename: ')
fileName = open(fileName, "r")
lst = []
for inputLine in fileName:
splittext = inputLine.split()
place = splittext[0]
locations = splittext[1]
lst += [locations]
print(lst)
print(median(lst))
main()
目前,
insertion\u sort
对程序没有任何意义。它尚未定义
如果您知道插入排序的工作原理,基本上可以从一个空列表开始并在其中放置数字。从一端开始,将插入的数字与列表中已有的数字进行比较,直到数字介于列表中已有的两个数字之间。然后插入并重复此过程
希望这足以指导您如何实现它。一些问题:
def distSum(lst,n):
sum==0
for current in lst:
sum=sum+abs(current-bestLoc)
return sum
sum
是一个内置函数;不要将其用作变量名(这会造成混淆,并阻止您调用该函数)sum=0
(将sum设置为0),而不是sum==0
(sum等于0吗?)bestLoc
?你从来没有定义过它。什么是n
?你从来没有使用过它。这个函数应该完成什么?它不清楚,你也没有记录或注释过它start\u time
,并且从不使用它lst_len = len(lst)
halflen = lst_len // 2
if lst_len % 2:
return lst[halflen]
else:
return (lst[halflen-1] + lst[halflen]) / 2
fileName
变量;这不是非法的,但容易混淆,尤其是对于大多数程序来说,它是一个文件对象,而不是文件名insertionSort
需要一个项目列表,并对列表进行排序
insertion_sort = lambda lst: lst.sort()
但这可能是作弊;-)您需要定义一个具有适当名称的函数,该函数只接受一个列表参数并执行一个命令。@jornsharpe他想让我们实现该算法:)谁说我想让您实现该算法?@thefourtheye我只是在寻求帮助-意思是如何实现该算法的指南?
lst_len = len(lst)
halflen = lst_len // 2
if lst_len % 2:
return lst[halflen]
else:
return (lst[halflen-1] + lst[halflen]) / 2
def main():
fileName = input('Enter a filename: ')
fileName = open(fileName, "r")
insertion_sort = lambda lst: lst.sort()