То, что вы делали неправильно, было именно тем, что вы указали в своих комментариях.Вы просто продолжали увеличивать e_pos
, и поэтому check_point
в конечном итоге оказалось больше, чем длина списка.
Я позволил себе сменить некоторые вещи, чтобы упростить процесс.Простые программы позволяют легче понять, что с ними не так.Убедитесь, что вы всегда стараетесь найти самый простой способ решить вашу проблему!Здесь я заменил потребность в e_pos
и previous_e_pos
, используя enumerate
:
string = '543987'
# Convert the sequence of strings into an array of numbers
conv_str_e = [int(i) for i in string]
#official code starts here
normal_list = []
list_of_small_nums = []
# this one will be used to decide if the element should go into the
#normal_list or list_of_small_nums
check_point = 0
for ind, e in enumerate(conv_str_e):
#The first element and every elements bigger the element with
#check_point as it's index
#will be put into the normal_list as long as the list inside
#list_of_small_nums is empty
if ind == 0 or e > conv_str_e[check_point]:
#If the list inside list_of_small_nums is not empty
if list_of_small_nums != []:
#concatenate the normal_list and list_of_small_nums
normal_list.append(list_of_small_nums)
#Clear the list inside list_of_small_nums
list_of_small_nums = []
#Add the element in the normal_list
normal_list.append(e)
# Update my trackers
check_point = ind
else:
#The curent element is not bigger then the element with the
#check_point as index position
#Therefore it goes into the sublist.
list_of_small_nums.append(e)
# If there is anything left, add it to the list
if list_of_small_nums != []:
normal_list.append(list_of_small_nums)
print(normal_list)
Результат:
[5, [4, 3], 9, [8, 7]]
Я уверен, что вы можете изменить его здесьчтобы вернуть его в вашу функцию.