# 15/15 Unable to halve the array

#1

In the hint it mentions “cutting the length of the array in half”
When I run the first bold line it doesn’t affect the length of a list at all, and when I use the second it says “list indices must not be floats”
What are the problems with what I’ve written? I would appreciate any feedback

``````def median(Lst):
sortLst = sorted(Lst)

if len(sortLst) % 2 == 0:
**len(sortLst) / 2.0**                                             # halve length of list
**sortLst = sortLst[len(sortLst) / 2.0]**
print sortLst
midNums = (sortLst[-1] + sortLst[-2]) / 2.0 # averages the middle numbers
return midNums

else:
len(sortLst) / 2.0
return sortLst[-1]
``````

#2

Lists are indexed data type, means we can access individual elements by passing index.
index must be an integer.

my_list = [1,2,3,4]
print(my_list[2]) # 3

Note - You can’t pass float(decimal numbers) to get the items.

print(my_list[2.0]) # Error (TypeError)

#3

here:

``````len(sortLst) / 2.0
``````

why do you use `2.0`? This will give a float result

#4

I got rid of that line and used:

``````sortLst = sortLst[len(sortLst) / 2]
``````

but I get this error: ‘int’ object has no attribute ‘getitem

#5

here:

``````    sortLst = sortLst[len(sortLst) / 2.0]
print sortLst
midNums = (sortLst[-1] + sortLst[-2]) / 2.0 # averages the middle numbers
``````

you make sortLst an integer (retrieving integer value from list), then you print this integer, and then you try to access integer by index, which won’t work. Integers can’t be accessed by index, that is for string and lists.

take a step back to think the logic of your program through

#6

How is

``````sortLst = sortLst[len(sortLst) / 2.0]
``````

making the list an integer instead of finding the middle indices?

#7

`len(sortLst) / 2` would give the middle index, then using this index (`sortLst[index]`)to retrieve value from list will give you the middle value.

#8

I think I was able to figure out what you meant in your previous post -> I was setting sortLst to the length of the list itself (as an integer) instead of accessing the indices.
I put

``````i = len(sortLst) / 2
``````

into it’s own variable and used

``````return (sortLst[i] + (sortLst[i-1])) / 2.0
``````

to actually get the values at the indices instead of just the indices themselves (3, 2/ 5, 4 etc.). Thank you for your help!

#9

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.