Your code looks well-formatted, it's easy to read and to follow, and the explanation you gave matches the code exactly. Well done. :)
for item in my_list:
This statement looks strange since in the body of this for
loop, you neither use item
nor my_list
. You can express the idea of that code more directly:
for _ in range(len(my_list)):
The variable _
is just a normal variable, and you could even access its value. By convention though, the variable _
means an unused variable.
Or, alternatively, you could express it even shorter:
while len(unsorted_list) > 0:
This wording matches the body of the loop, where you remove an element from unsorted_list
in each iteration. This is good. It's still quite long though, therefore the idiomatic way to test whether a list is empty is:
while unsorted_list:
This makes your code:
def my_sort(my_list):
unsorted_list = [*my_list]
sorted_list = []
while unsorted_list:
shortest_num = inf
for num in unsorted_list:
if num < shortest_num:
shortest_num = num
unsorted_list.remove(shortest_num)
sorted_list.append(shortest_num)
return sorted_list
This code can be made much shorter since Python has a built-in function called min. By using it you can transform your code to:
def my_sort(my_list):
unsorted_list = [*my_list]
sorted_list = []
while unsorted_list:
shortest_num = min(unsorted_list)
unsorted_list.remove(shortest_num)
sorted_list.append(shortest_num)
return sorted_list
This is already much shorter than before, and you don't need to import math.inf
anymore, which is good, since it was a placeholder anyway that was not really necessary from a high-level point of view.
This is about as elegant as it gets. You should not use this sorting algorithm for sorting large data since for a list of \$n\$ elements it requires \$ n + n \cdot (\frac n2 + \frac n2 + 1) \$ steps, or a bit more compressed, it has the time complexity \$\mathcal O(n^2)\$. There are faster sorting algorithms out there. These are more complicated to implement, but once they are implemented and tested, they are as easy to use as your algorithm.
Regarding the variable names: shortest_num
should better be smallest_num
, since 0
is shorter than -12345
, and you probably didn't mean that. Your documentation comment should be more like:
"""
Return a sorted copy of the given list, from smallest to largest.
"""
# Sorting is done by repeatedly removing the smallest
# number from the list and adding it to the sorted list.
Note how I split the comment into two separate parts.
The upper half in the """ triple quotes """
is meant to document the behavior of the code, while the lower half explains the implementation. For the code that uses this sorting function, it doesn't matter how the list is sorted, it just matters that it is sorted.
shortest_num
and callunsorted_list.remove()
, which is itself O(N), and will be slower and non-scalable. I presume you want to know that, rather than comments on your syntax. \$\endgroup\$