4

I want to sort words in a list based on length.

The test case is {'cat','jump','blue','balloon'}

When run through this method it will print something along the lines of:

{'balloon','jump','blue','balloon'}

Another problem I have run into, is that the type of python we were using worked fine, however when I try to run the .py in the Python 3.5.2 shell, it comes up with errors.

I mainly just need to know what I did wrong, and what I can do to fix it so that it works. Any help is appreciated!

The .py file can be found here:

def wordSort():
    words = []
    minimum = 'NaN'
    index = 0
    x = 0    
    y = 0    
    z = 1
    #How many words to be entered
    length = input('How many words would you like to enter? ')
    #Put words in the number of times you entered previously    
    while not z >= length + 1:
        words.append(raw_input('Enter word #' + str(z) + ': '))
        z += 1
    while x < length:
        minimum = words[x]
        #Goes through the list and finds a smaller word
        while y < length:
            if len(words[y]) < len(minimum):
                minimum = words[y]
                index = y
            y += 1
        words[index] = words[x]
        words[x] = minimum
        x += 1
    print words
jophab
  • 4,386
  • 9
  • 37
  • 54
Kobe Goldman
  • 41
  • 1
  • 2
  • 1
    Possible duplicate of [How to sort a list of objects , based on an attribute of the objects?](http://stackoverflow.com/questions/403421/how-to-sort-a-list-of-objects-based-on-an-attribute-of-the-objects) – congusbongus Apr 04 '17 at 04:17
  • 1
    This is python 2.x (presumably 2.7) code. It needs to either be run under python 2.x or adjusted for python 3. – i336_ Apr 04 '17 at 04:35

2 Answers2

7
  • print is a function in Python 3.5 and needs to be used as print(words). Read more about it here
  • Given a list of words this can be used to sort them according to length of string using sorted:

    sorted(word_list , key = len)

xssChauhan
  • 2,202
  • 1
  • 15
  • 34
3

Try this. It will sort the list based on length of strings in ascending order

list_name.sort(key=len)

For descending order,

list_name.sort(key=len,reverse=True)
jophab
  • 4,386
  • 9
  • 37
  • 54