indexError: ошибка индексации списка и неправильное отслеживание счетчиков - PullRequest
3 голосов
/ 07 июля 2019

Цель программы - определить процедуру, которая принимает строку чисел от 1 до 9 и выводит список со следующими параметрами: Каждое число в строке должно быть вставлено в список.

Если число x в строке меньше или равно предыдущему числу y, число x должно быть вставлено в подсписок.Продолжайте добавлять следующие числа в список до достижения числа z, которое больше числа y.

Затем добавьте это число z в обычный список и продолжите.

#testcases
string = '543987'
numbers_in_lists(string)
result = [5,[4,3],9,[8,7]]
def numbers_in_lists(string):
    # Convert the sequence of strings into an array of numbers
    i = 0
    conv_str_e = []
    while i < len(string):
        conv_str_e.append(int(string[i]))
        i += 1

    #official code starts here
    normal_list = []
    list_of_small_nums = [[]]

    # This will help me keep track of elements of the normal_list.
    previous_e_pos = -1
    e_pos = 0

    # 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 e in 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 e_pos == 0 or e > conv_str_e[check_point]:

            #If the list inside list_of_small_nums is not empty
            if list_of_small_nums[0] != []:

                #concatenate the normal_list and list_of_small_nums
                normal_list = normal_list + list_of_small_nums[0]

                #Clear the list inside list_of_small_nums
                list_of_small_nums[0] = []

            #Add the element in the normal_list
            normal_list.append(e)

            # Update my trackers
            e_pos += 1
            previous_e_pos += 1

            # (not sure this might be the error)
            check_point = e_pos

        #The curent element is not bigger then the element with the 
        #check_point as index position
        #Therefor it goes into the sublist.

        list_of_small_nums[0].append(e)
        e_pos += 1
        previous_e_pos += 1

    return list

1 Ответ

1 голос
/ 07 июля 2019

То, что вы делали неправильно, было именно тем, что вы указали в своих комментариях.Вы просто продолжали увеличивать 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]]

Я уверен, что вы можете изменить его здесьчтобы вернуть его в вашу функцию.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...