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
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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With