Task 1
Sorting using the built in function
14.1: sort.py
words = ["Five", "Four", "Three", "Two", "One"]
print("Original List:", words)
print("Sorted List:", sorted(words))
# Checks to make sure I used the correct method, that does not mutate the list
assert words != ["Five", "Four", "One", "Three", "Two"]
Output
>>> Original List: ['Five', 'Four', 'Three', 'Two', 'One']
>>> Sorted List: ['Five', 'Four', 'One', 'Three', 'Two']
Task 2
Index | List |
---|---|
0 0 | ['One', 'Two', 'Three', 'Four', 'Five'] |
0 1 | ['One', 'Three', 'Two', 'Four', 'Five'] |
0 2 | ['One', 'Three', 'Four', 'Two', 'Five'] |
0 3 | ['One', 'Three', 'Four', 'Five', 'Two'] |
1 1 | ['One', 'Four', 'Three', 'Five', 'Two'] |
1 2 | ['One', 'Four', 'Five', 'Three', 'Two'] |
2 0 | ['Four', 'One', 'Five', 'Three', 'Two'] |
2 1 | ['Four', 'Five', 'One', 'Three', 'Two'] |
3 0 | ['Five', 'Four', 'One', 'Three', 'Two'] |
The following is the efficient program I used to get this table
Source: 14.2 bubble b.py
numbers = ["One", "Two", "Three", "Four", "Five"]
max_index = len(numbers) - 1
# Bubble Sort program
for i in range(max_index):
_numbers = numbers.copy()
for j in range(max_index - i):
# Checks if the current element is greater than the next element
if numbers[j] > numbers[j + 1]:
# Swaps the elements
(numbers[j], numbers[j + 1]) = (numbers[j + 1], numbers[j])
if _numbers == numbers:
# We finished an entire pass without swapping so we can quit
break
print(numbers)
And also the inefficient program that yields the same output
Source: 14.2 bubble a.py
numbers = ["One", "Two", "Three", "Four", "Five"]
max_index = len(numbers) - 1
# Bubble Sort program
for i in range(max_index):
for j in range(max_index - i):
# Checks if the current element is greater than the next element
if numbers[j] > numbers[j + 1]:
# Swaps the elements
(numbers[j], numbers[j + 1]) = (numbers[j + 1], numbers[j])
print(numbers)
The difference between these programs is that the efficient one checks every iteration if we need to keep iterating.
I was curious, however, if it was actually more efficient. For lists that are partially already sorted, it is way more efficient, up to 3x.
But for this list, it is not. In fact it added more operations than the original program.
This demonstrates the difference between the two, and the thought that must go into choosing methods such as these in production programs, especially when an extra couple of operations can make all the difference.