Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a list of words by length

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
like image 789
Kobe Goldman Avatar asked Dec 24 '22 19:12

Kobe Goldman


2 Answers

  • 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)

like image 193
xssChauhan Avatar answered Jan 05 '23 15:01

xssChauhan


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)
like image 44
jophab Avatar answered Jan 05 '23 15:01

jophab