Mar-27-2024, 09:34 AM
Following your private message:
1. It seems a bit strange to me to check your sort method by using sorted(). If you have already sorted, why do it again?
2. Why make life difficult by adding 0 at the beginning? Add zero after sorting if you really need a 0 there.
Python implements timsort for sorting. Have a look here for various sorting methods and how efficient they are.
If you really need 0 do this after sorting:
1. It seems a bit strange to me to check your sort method by using sorted(). If you have already sorted, why do it again?
2. Why make life difficult by adding 0 at the beginning? Add zero after sorting if you really need a 0 there.
Python implements timsort for sorting. Have a look here for various sorting methods and how efficient they are.
Quote:The Timsort Algorithm in Python
The Timsort algorithm is considered a hybrid sorting algorithm because it employs a best-of-both-worlds combination of insertion sort and merge sort. Timsort is near and dear to the Python community because it was created by Tim Peters in 2002 to be used as the standard sorting algorithm of the Python language.
nums = '5 1 3 4 2' frog_list = [int(x) for x in nums.split()] move_count = position = direction = 0 sorted_frogs = sorted(frog_list, reverse=True) while frog_list != sorted_frogs: if direction == 0: if frog_list[position] == frog_list[-2]: frog_list[position], frog_list[position + 1] = frog_list[position + 1], frog_list[position] position += 1 elif frog_list[position] == frog_list[-1]: direction = 1 elif frog_list[position + 2] > frog_list[position + 1]: frog_list[position], frog_list[position + 2] = frog_list[position + 2], frog_list[position] position += 2 else: frog_list[position], frog_list[position + 1] = frog_list[position + 1], frog_list[position] position += 1 elif direction == 1: if frog_list[position] == frog_list[1]: frog_list[position], frog_list[position - 1] = frog_list[position - 1], frog_list[position] position -= 1 elif frog_list[position] == frog_list[0]: direction = 0 elif frog_list[position - 2] < frog_list[position - 1]: frog_list[position], frog_list[position - 2] = frog_list[position - 2], frog_list[position] position -= 2 else: frog_list[position], frog_list[position - 1] = frog_list[position - 1], frog_list[position] position -= 1 move_count += 1 print(f'{frog_list}, moves = {move_count}, position = {position}, direction = {direction}')You can see from the output that it works, but the 5 bounces around in the first 6 lines. Fix that if you can.
If you really need 0 do this after sorting:
frog_list.insert(0, 0)