sorted(list) versus list.sort()
This code for finding median gives the error message: median([1]) resulted in an error: object of type ‘NoneType’ has no len()
def median(ListIn): ListIn = ListIn.sort() n = len(ListIn) if n % 2 == 0: return (ListIn[n/2-1] + ListIn[n/2])/2.0 else: return ListIn[(n-1)/2]
But why does it work when
ListIn = ListIn.sort() is replaced with
ListIn = sorted(ListIn)?
Answer 548e5f1f86f5521305007e9d
list.sort and
sorted are different objects, they do different things
both are callable, one is a method and the other is a function
since they behave differently you will have to use them differently, even if their purposes are largely the same
list.sort has no return value, instead it has the side effect that the instance of list that it was called on will be sorted after the method has finished
sorted leaves the argument unchanged and instead creates and returns a list consisting of the same elements as the argument that you passed to it
you can look them up in python’s documentation, or you can call the function help:
help(sorted) help(list.sort)
output:
Help on built-in function sorted in module __builtin__: sorted(...) sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list
basically says it takes one argument that you have to supply and then a couple of optional ones, you’d have to look them up for what those optional ones do
-
Help on method_descriptor: sort(...) L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*; cmp(x, y) -> -1, 0, 1
only optional arguments, and they are the same as that of sorted, cmp, key and reverse - you can probably guess what the reverse one does, the others need to be looked up
documentation for sorted: list.sort: (it happens to refer to the documentation of sorted for the full documentation)
the 2 in the url’s can be changed to 3 for python 3 documentation. notably sorted will not return a list, it instead returns an iterable (an object that will yield values when you ask for it, but until you do it does not get evaluated. for example, xrange(1000000) doesn’t make a list of a million integers, instead it gives you one integer at a time and computes the next one each time you ask for it - this is called lazy evaluation
Answer 54f8952f51b8875ecc005c3f
This is mine, works fine::
def median(lists): lists = sorted(lists) n = len(lists) if n % 2 == 0: return (lists[n/2-1] + lists[n/2])/2.0 else: return lists[(n/2)] print median([1, 2, 4])
this one is the most readable and very easy to understand… good job, thanks
QABANBAIBATYR, you are absolutely right
This makes so much sense!! Thanks!!
why does it matter if you type in 2.0 vs just 2 at the end of your first return
thanks
2.0 casts the results as a float (has decimals). Another way you can do it is wrap the entire argument with float() to cast.
why did you, in the else statement put brackets inside the list lists[(n/2)] does it matter if you put them there
ok thx
can someone explain why there is -1 in the first return line? i know it works, but shouldn’t it be plus..
Exactly. The list length is, say, 3, but Python gives the items indexes of [0,1,2].
what if the length of the list is odd (“let’s say 5”) , how comes it’s possible to divide odd over 2===> 5/2 to get the index of the median! that doesn’t make sense to me! help please!
so simple than i think…thanks
Bassam i think because its not a float the program reads 5/2 as 2, not 2.5
Answer 55b711b276b8fe3c230007dd
This will also work…
import numpy def median(list): return numpy.median(list) print median([1,2,3,4,5])
Simplest code I’ve seen for this exercise,and it works.
Answer 54e2712976b8feb615000917
Well, say list = [“Hi”, “my name”, “is James”] if you say sorted(list) then it takes the sorted list as an argument, but doesn’t actually do anything to the list, if you print it it will give [“Hi”, “my name”, “is James”], but if you do list.sort() then print the list, it will give [“Hi”, “is James”, “my name”]
Dammit Texenox.
Answer 55362486d3292f5eda00012c
list.sort() rearranges the list.
sorted(list) has to be assigned.
i.e.
sorted_list = sorted(unsorted_list)
Yeah this took me a while to figure out because if you just write down sorted(x) in your function it doesn’t produce an error.
Yeah, you have to say something such as myList=sorted(myList) or another line with the same meaning.
Answer 5614a7b4e39efe53a200025e
Answer 54a36a7e76b8feae040174d7
I still haven’t fully understood this exercise :/
Answer 54b7929d76b8fe804c001cc4
Here is my code that works 100%
So I get why this works, and it’s a very neat piece of code, but the part I get is why does;
return srtlst[int(len(srtlst)/2+0.5)]
work? Does the addition of the 0.5 automatically make the division result into a float? I thought this would return an integer and then convert to a float once you add on the 0.5?
The +0.5 is completely erroneous as the float is immediately converted back to an integer by the int() function included in the line. Without the int() function, however, an error would be returned since list indices must be integers and not floats. Better would be “return srtlst[len(srtlst)/2]”
My guess is that libeadier was thinking if he divided an odd list length by 2 he would always have 0.5 remaining and needed to correct for this. For an entry=[1, 2, 3, 4, 5], one would think that len(entry)/2 would return 2.5. However, the len() function is an integer, so it will return 2 instead of 2.5. This is fine though since we WANT index 2 and not 3 as I suspect libeadier was trying to get. You have to remember that lists begin counting at 0!
Answer 54e1d5c8d3292fcb3a001668
def median(lst): lst = sorted(lst)
if len(lst) == 1 or len(lst) == 0: return lst[0] elif len(lst) > 1 and len(lst) % 2 == 0: median = (lst[len(lst) / 2] + lst[len(lst) / 2 - 1]) / 2.0 return median else: median = lst[(len(lst) - 1) / 2] return median
Answer 54e3651a51b887b23a002457
Answer 54f694459113cb0206000d32
Answer 55d4164193767600490004f5
Answer 55d8c11ad3292fe43a0000f2
Why is it necessary to have the decimal point for 2.0 in line five? I have a feeling this was covered before but I can’t remember. It doesn’t work with just 2, why is this?
Answer 54d1fbb951b8877af6001c2a
def median(the_list): new_list=sorted(the_list) middle_number= len(new_list)/2
if len(new_list)==1: return new_list[0] else: if len(new_list)%2==0:
return (new_list[middle_number-1]+new_list[middle_number])/2.0 else: return new_list[middle_number]
Basicaly mine answer doesn’t add anything except “readability” which counts and helps in programming.
You don’t need that first if statement, If len(newlist) == 1 then the calculations performed below will still come up with the correct median.
However, your code does not work with an empty list, it’ll show an error, so you might want to make your first if statement: if len(newlist == 0: return 0
Also make sure are your variables are typed the same. The variable newlist sometimes appears as new_list and middlenumber sometimes appears as middle_number.
Answer 55630acd9113cba3190004a9
def median(listn): result = sorted(listn) ln = len(result) if ln % 2 == 0: return (result[ln/2 - 1] + result[ln/2])/2.0 elif len(result) == 1: return result[0] else: return result[(ln / 2)]
If you see something that’s incorrect or something that can be shorter pls commen :)
You could cut out the elif lines completely and the code will still run the same way.
Answer 5569749576b8fe8d4200015d
Thats my 8-lines of code that worked well
def median(lista): new_list = sorted(lista) odd_avg = new_list[(len(new_list) - 1)/2] even_avg = (new_list[(len(new_list)/2)] + new_list[((len(new_list)/2) - 1)]) / 2.0 if len(new_list) % 2 == 0: return even_avg else: return odd_avg
Answer 559e7c86937676c0c700020d
def median(lst): lst = sorted(lst) n = len(lst) if n % 2 == 0: x = lst[n / 2] y = lst[(n / 2) - 1] return ((x + y) / 2.0) elif n == 1: return lst[0] else: return lst[(n - 1) / 2]
Thanks for your explanation; it’s way more helpful than Python’s documentation.
In short, list.sort() sorts the given list, but sorted(list) does not modify that list – it only returns a sorted copy of that list.