I am attempting to sort a Python list of ints and then use the .pop() function to return the highest one. I have tried a writing the method in different ways:
def LongestPath(T):
paths = [Ancestors(T,x) for x in OrdLeaves(T)]
#^ Creating a lists of lists of ints, this part works
result =[len(y) for y in paths ]
#^ Creating a list of ints where each int is a length of the a list in paths
result = result.sort()
#^meant to sort the result
return result.pop()
#^meant to return the largest int in the list (the last one)
I have also tried
def LongestPath(T):
return[len(y) for y in [Ancestors(T,x) for x in OrdLeaves(T)] ].sort().pop()
In both cases .sort() causes the list to be None (which has no .pop() function and returns an error). When I remove the .sort() it works fine but does not return the largest int since the list is not sorted.
Simply remove the assignment from
leaving just
The
sortmethod works in-place (it modifies the existing list), so it returnsNone. When you assign its result to the name of the list, you’re assigningNone. So no assignment is necessary.But in any case, what you’re trying to accomplish can easily (and more efficiently) be written as a one-liner:
maxoperates in linear time, O(n), while sorting is O(nlogn). You also don’t need nested list comprehensions, a single generator expression will do.