Reputation: 179
import math
def getBestLoc(lst):
if len(lst) % 2 == 0:
#bestLoc = (lst((len(lst)/2) + lst(len(lst)/2)-1))/2
bestLoc = ((lst[len(lst)]//2) + (lst[len(lst)/2]-1)) // 2
else:
bestLoc = lst(len(lst)//2)
sumOfDistances(lst, bestLoc)
return bestLoc
def sumOfDistances(lst, bestLoc):
total = 0
for i in lst:
total += math.abs(bestLoc - i)
return total
def main():
lst = [10, 15, 30, 200]
lst.sort()
print(lst)
getBestLoc(lst)
main()
I got this error:
Traceback (most recent call last):
File "C:\Users\NAME\Desktop\storeLocation.py", line 32, in <module>
main()
File "C:\Users\NAME\Desktop\storeLocation.py", line 30, in main
getBestLoc(lst)
File "C:\Users\NAME\Desktop\storeLocation.py", line 14, in getBestLoc
bestLoc = ((lst[len(lst)]//2) + (lst[len(lst)/2]-1)) // 2
IndexError: list index out of range
I don't know what I did wrong. It is saying, IndexError: list index out of range
, I don't know what that means. It is my lab homework. Trying to figure this issue out. Any help? Thanks.
Upvotes: 0
Views: 243
Reputation: 300
What other posters have said. Use square brackets []
instead of parentheses ()
to access list elements. eg. lst[index]
Also, you are attempting to access elements outside the list.
Don't use lst[len(lst)]
- you automatically get an index out of bounds exception.
Instead, use lst[len(lst)-1]
.
Also, don't use math.abs, that function doesn't exist in python. Instead use math.fabs
Upvotes: 1
Reputation: 891
You're attempting to use lst
as a function by using lst(...)
. Try using square brackets lst[...]
.
Upvotes: 2
Reputation: 33046
You need to access an element of the list with []
, not to call it as a function with ()
. Replace:
bestLoc = ((lst(len(lst))/2) + (lst(len(lst)/2)-1)) / 2
with
bestLoc = ((lst[len(lst)]/2) + (lst[len(lst)/2]-1)) / 2
Upvotes: 4
Reputation: 1787
accessing list element uses square bracket [] not ()
should be
((lst[len(lst)]/2) + (lst[len(lst)/2]-1)) / 2
same thing with the else: clause
Upvotes: 2