我正在尝试创建一个实现快速选择算法的程序,以查找列表的中位数;然后将该中位数用于计算列表中每个其他元素与其自身之间的差异。
例如,
mget(letters[24:26]) %>% enframe(name = "A", value = "B") %>% unnest
会返回
lstMedian = 2
sumDifference是
x = 2-sortedList [0]
y = 2- sortedList [2]
sumDifference = x + y
在大多数情况下,我都能实现这一点,具有偶数和奇数个元素的排序列表可以与所有未排序的奇数长度列表一起使用,但是,对于未排序的偶数长度列表而言并非如此。
使用随机生成的未排序的偶数长度列表进行的追溯是:
lst = [1,3,2]
sortedList = [1,2,3]
我正在使用3个主要函数来计算:
sumDistance:
Traceback (most recent call last):
[26, 66, 43, 47, 73, 75, 52, 81, 21, 73, 32, 92]
File "~store_location.py", line 102, in <module>
main()
X: 63
File "~store_location.py", line 96, in main
y = quickSelect(lst, x)
File "~store_location.py", line 77, in quickSelect
return quickSelect(largerList, k - m - count)
File "~store_location.py", line 77, in quickSelect
return quickSelect(largerList, k - m - count)
File "~store_location.py", line 77, in quickSelect
return quickSelect(largerList, k - m - count)
File "~store_location.py", line 79, in quickSelect
return aList[0]
IndexError: list index out of range
找到中位数指数:
def sumDistance(lst, median):
"""
Find the total distance from each building to the optimal store location
:param lst: Given list
:param median: Calculated median of give list
:return: sum of distances
"""
total = 0
for location in range(0, len(lst) - 1):
total += abs(median - lst[location])
return total
查找中值:
def quickSelectHelper(L):
"""
Find the index of the correct median depending on the length of the list (odd or even)
:param L: Given list
:return: the Median the needs to be translated (k'th element)
"""
if len(L) % 2 == 0 and len(L) >= 2:
idx1 = int((0.5 * len(L)) - 1)
idx2 = (len(L) // 2)
calculatedMedian = (L[idx1] + L[idx2]) // 2
elif len(L) % 2 != 0 and len(L) >= 1:
calculatedMedian = (0.5 * len(L)) - 0.5
return calculatedMedian
如果我的背景缺乏,请随时关注entirety of my code(约100行)
答案 0 :(得分:0)
递归基本情况的返回不正确。当使用quickSelect
调用aList=[]
时,即使return aList[0]
为空(并且aList
始终是IndexError),您[][0]
也是如此。不确定什么是您的基本情况(None
?),但是您可能还必须在调用quickSelect
的任何情况下进行处理。