Indexerror: list index out of range in python

Asked

Viewed 1,380 times

0

inserir a descrição da imagem aqui

With the comoda configuration input and output the number of inaccessible drawers .

I have this code now

configuração = []
lista = []
aberto = 0

gavetas = int(input('Quantas Gavetas ? -->  '))
print('Configuração das gavetas :')
for c in range(0,gavetas ):
    z = input()
    configuração.append(z)

for a in configuração :
    if a == 'o':
        lista.append('aberta')
    if a == '#':
        lista.append('fechada')
if not 'aberta' in lista:
    print(gavetas, 'todas estão fechadas ')
else:
    if not 'fechada' in lista:
        print(0,'Todas abertas')
    else:
        while len(lista) > 0:
            if lista[0] == 'fechada':
                while lista[0] == 'fechada':
                    del lista[0]

            if lista[0] == 'aberta':
                if len(lista) == 1:
                    print(gavetas-1)
                else:
                    if lista[1] == 'fechada':
                        del lista[0]
                        del lista[0]
                        aberto = aberto + 2
                    elif lista[1] =='aberta':
                        del lista[0]
                        del lista[0]
                        aberto = aberto + 2

 print(gavetas-aberto)

The code may seem a little strange is because I’ve remade so many stools ... Every time I run the program starting by opening 'o' it gives the error of

while lista[0] == 'fechada':
IndexError: list index out of range

I have tried to do it in many ways but I am not really able to solve this problem !

example of input

o
#
#
#

Expected output

2

output

while lista[0] == 'fechada':
IndexError: list index out of range

1 answer

0


The error happened because you are trying to access position 0 from an empty list.

...

if lista[0] == 'fechada':
    while lista[0] == 'fechada':
        del lista[0]

...

At this point in the code, lista will be ['fechada']; the condition of if is validated and executes the repeat loop; as the first element is 'fechada' he is excluded, getting lista = []; the loop condition will be validated again and... error occurs as there is no position 0 in the list.

I debug your code and see how it runs:

inserir a descrição da imagem aqui

Note: I simplified the input, leaving the list fixed instead of reading from the user and added a print(lista) in the part of the code that gives the error for you to track the current value of lista.


The solution is much simpler than that:

  • If the drawer is open is accessible;
  • If it is locked:
    • And is the first is inaccessible or
    • The previous one is also locked is inaccessible;

The code for that is:

gavetas = ['o', '#', 'o', '#']

inacessiveis = 0

for posicao, gaveta in enumerate(gavetas):

    # Se a gaveta está aberta é acessível
    if gaveta == 'o':
        continue

    # Se está trancada:
    # - E é a primeira é inacessível ou
    # - A anterior também está trancada é inacessível
    if posicao == 0 or gavetas[posicao-1] == '#':
        inacessiveis += 1

print(inacessiveis)

This already solves the problem for all foreseen situations.

You can even simplify the code for just one condition:

for posicao, gaveta in enumerate(gavetas):
    if gaveta == '#' and (posicao == 0 or gavetas[posicao-1] == '#'):
        inacessiveis += 1

If you want dig deeper, you can solve with just one expression:

inacessiveis = sum(
    gaveta == '#' and (posicao == 0 or gavetas[posicao-1] == '#') 
        for posicao, gaveta in enumerate(gavetas)
)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.