Jason Rutz published the original problem in Python on edabit.com
A student learning Python was trying to make a function that sorts all the letters of a word, but their code is broken, and they can’t figure out why.
Spot and fix the error(s) in the code to make the function work. As an added challenge for those who are more advanced, see if you can shrink (the fixed version of) the student’s code down to only a single line.
Code
def sort_word(word):
word = word.split('')
word = list(word.sort())
final_word = ''
for char in word
final_word = final_word + char
return final_word
Examples
sort_word("dcba") ➞ "abcd"
sort_word("Unpredictable") ➞ "Uabcdeeilnprt"
# Capital letters should come first.
sort_word("pneumonoultramicroscopicsilicovolcanoconiosis") ➞ "aacccccceiiiiiilllmmnnnnooooooooopprrsssstuuv"
Notes
If you’re trying to get a function definition into a single line, try assigning a variable to a lambda function.
Solution
The student is trying to create a function that sorts all the letters of a word. The code is broken because of the following issues:
- In the first line, the student is trying to split the word using an empty string, but the split function expects a delimiter as an argument. To convert the word into a list of letters, the student should use the list() function.
- In the second line, the student is trying to sort the list returned by list(), but the list() function returns a new list and does not have a sort() method. So, the student should use the sort() method on the returned list.
- In the for loop, the student is missing a colon at the end of the for loop.
- In the return statement, final_word is initialized as an empty string and in the loop we are concatenating the characters, but python’s string are immutable, so it will be more efficient to use list.
Corrected code:
def sort_word(word):
word = list(word)
word.sort()
final_word = ''.join(word)
return final_word
The above code can also be written in a single line:
sort_word = lambda word: ''.join(sorted(list(word)))