Mar-31-2024, 03:11 AM
Frog codility leap sort variant
Desired output :
input_str = input("Enter Frogs: ") # User types 5 1 3 4 2 <enter>. Do not type the zero. frog_list = [0] for number_str in input_str.split(): frog_list.append(int(number_str)) sorted_frogs = [0] + sorted(frog_list[1:], reverse=True) frog_count = len(frog_list) - 1 print(frog_list, sorted_frogs, frog_count)My attempt :
input_str = input("Enter Frogs: ") # User types 5 1 3 4 2 <enter>. Do not type the zero. frog_list = [0] for number_str in input_str.split(): frog_list.append(int(number_str)) sorted_frogs = [0] + sorted(frog_list[1:], reverse=True) frog_count = len(frog_list) - 1 move_count = 0 position = 0 direction = 0 print(frog_list) if frog_count == 1: move_count = 0 else: 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(frog_list) move_count = move_count print('Minimum number of moves: ', move_count)Current output:
Output:Enter Frogs: 5 1 3 4 2
[0, 5, 1, 3, 4, 2] [0, 5, 4, 3, 2, 1] 5
[Program finished]
Can anyone make the code show the stepsDesired output :
Output:Output:
[0, 5, 1, 3, 4, 2]
[2, 5, 1, 3, 4, 0]
[2, 5, 0, 3, 4, 1]
[2, 5, 4, 3, 0, 1]
[0, 5, 4, 3, 2, 1]
Minimum number of moves: 4
You can help me improve my code or you can share a whole code that do this better since i'm not really good at changing small part of code if you give me one, sorry for that, thank you so much