Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
sort_by_length
#1
"""
Create a function called sort_by_length, which takes a single argument - a
(immutable) sequence of iterables (L).

The function must:
  1. Return a new list, which contains all strings from L, sorted by their
  lengths, so that the *longest ones come first*
  2. The function documentation should read:
    Sort a list by descending length of its elements
"""

def sort_by_length(*args):
    """ Sort a list by descending length of its elements """
    x = args[0]
    y = type(x)
    if (y == tuple):
        x = list(x)
    x.sort()
    x.reverse()
    print (x)

arg = [4,1,3,2,5]"""
arg = ['ab','imdb','nls']
sort_by_length(arg)
It is working for numbers, strings it is sorting in reverse order, but how to sort by length of objects
Reply
#2
You need to use the key parameter of the sort method. It takes a function that takes one parameter (the item being sorted) and returns the value to sort by.

I don't think that's a good use of *args. I would just write this with one parameter.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
Here is a solution for a list of strings.
(For a list of numbers, you still have to improve the code):

#python3
def sort_by_length(list_to_sort):
    list_sorted = sorted(list_to_sort, key=len, reverse=True)
    return list_sorted

#test
print(sort_by_length( ('ab', 'imdb', 'nls') ))
print(sort_by_length( ['ab', 'imdb', 'nls'] ))
Reply
#4
Why would you make it work for numbers?  The question doesn't have anything to do with numbers, as it specifically says you're sorting a list, where each element of the list-to-be-sorted is itself an iterable.  A number is not an iterable.  Which means you can do this very easily by using the builtin function len(), since that works with all iterables.  

...also, you're told the original list you're given is supposed to be immutable, which means you shouldn't modify it... which is exactly what you ARE doing (sort() mutates the original list).  Checking the type to see if it happens to be a tuple, and boxing it into a list isn't a good way to get around it, you should just use a non-mutating sort function, such as sorted().

https://docs.python.org/3.6/library/functions.html#len Wrote:len(s)
Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).

https://docs.python.org/3.6/library/func...tml#sorted Wrote:sorted(iterable[, key][, reverse])
Return a new sorted list from the items in iterable.

Has two optional arguments which must be specified as keyword arguments.

key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly).

reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.

Use functools.cmp_to_key() to convert an old-style cmp function to a key function.

The built-in sorted() function is guaranteed to be stable. A sort is stable if it guarantees not to change the relative order of elements that compare equal — this is helpful for sorting in multiple passes (for example, sort by department, then by salary grade).

For sorting examples and a brief sorting tutorial, see Sorting HOW TO.

For the lazy, that means you could just do this:
sort_by_length = lambda x: sorted(x, key=len, reverse=True)
Reply
#5
Question:

Why:
def sort_by_length(*args):
    """ Sort a list by descending length of its elements """
    x = args[0]
    y = type(x)
when you can do the simpler and more readable:
def sort_by_length(x):
    """ Sort a list by descending length of its elements """
    y = type(x)
Is this some kind of fetish? Or just ignorance?
Unless noted otherwise, code in my posts should be understood as "coding suggestions", and its use may require more neurones than the two necessary for Ctrl-C/Ctrl-V.
Your one-stop place for all your GIMP needs: gimp-forum.net
Reply
#6
(Nov-30-2016, 04:45 PM)Ofnuts Wrote: Question:

Why:
def sort_by_length(*args):
    """ Sort a list by descending length of its elements """
    x = args[0]
    y = type(x)
when you can do the simpler and more readable:
def sort_by_length(x):
    """ Sort a list by descending length of its elements """
    y = type(x)
Is this some kind of fetish? Or just ignorance?

(Nov-30-2016, 05:42 PM)roadrage Wrote:
(Nov-30-2016, 04:45 PM)It is not fetish neither ignorance.... its called learning phase... ( i guess initially you are just focused on solving the problem, eventually  you\ll learn doing it the smarter way ) Ofnuts Wrote: Question:

Why:
def sort_by_length(*args):
    """ Sort a list by descending length of its elements """
    x = args[0]
    y = type(x)
when you can do the simpler and more readable:
def sort_by_length(x):
    """ Sort a list by descending length of its elements """
    y = type(x)
Is this some kind of fetish? Or just ignorance?
Reply
#7
Quote:It is not fetish neither ignorance.... its called learning phase... ( i guess initially you are just focused on solving the problem, eventually you\ll learn doing it the smarter way )
It's a very, very odd way to do it. Using variadics is not an introductory thing to do... did you perhaps start learning a different language before moving to python?
Reply
#8
(Nov-30-2016, 05:42 PM)roadrage Wrote: It is not fetish neither ignorance.... its called learning phase... ( i guess initially you are just focused on solving the problem, eventually you\ll learn doing it the smarter way )

You are the first "learner" to use this (and we have seen quite a few here). Named parameters are more readable and less prone to errors.
Unless noted otherwise, code in my posts should be understood as "coding suggestions", and its use may require more neurones than the two necessary for Ctrl-C/Ctrl-V.
Your one-stop place for all your GIMP needs: gimp-forum.net
Reply
#9
(Dec-01-2016, 11:32 PM)Ofnuts Wrote: You are the first "learner" to use this (and we have seen quite a few here). Named parameters are more readable and less prone to errors.
Not to mention varargs are an advanced feature.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020