Help to understand where the error is:
a = [] N = 2015 for i in range(0, N): a.append(int(input())) b = -1 for i in range(1, N-1): if (b == -1 or a[i] < b) and (a[i] < a[i - 1]) and (a[i] < a[i + 1]): b = a[i] if b == -1: print('0') else: print(b) Help to understand where the error is:
a = [] N = 2015 for i in range(0, N): a.append(int(input())) b = -1 for i in range(1, N-1): if (b == -1 or a[i] < b) and (a[i] < a[i - 1]) and (a[i] < a[i + 1]): b = a[i] if b == -1: print('0') else: print(b) It seems that this question does not correspond to the subject of the site. Those who voted to close it indicated the following reason:
Line 4:
a.append( int( input() ) ) # Здесь вы заполняете значение массива с ключём [0]. То есть a[0]. Line 6:
for i in range(1, N-1): # Здесь вы запускаете цикл, в котором при первой итерации i будет равно 1. Line 7:
if (b == -1 or a[i] < b) and (a[i] < a[i - 1]) and (a[i] < a[i + 1]): # Здесь вы используете массив `a`. Конкретно: его значение под ключём i. i = 1, # но у вас заполнен только нулевой ключ массива. (Строка 4) This is what causes your error: IndexError: list index out of range
range (0, N-1) differ from range (1, N-1) ?)) - Don2Quixote a = [] minimum = -1 N = 2015 for i in range(0, N): a.append(int(input())) for i in range(0, N-1): if a[i] < a[i-1] and a[i] < a[i + 1] and (a[i] < minimum or minimum == -1): minimum = a[i] print(minimum if minimum != -1 else 0) The mistake is that you start traversing an array to calculate a hole, after each input of a new element. Including after entering the first one, when a [i - 1]) or a [i + 1] simply cannot exist. If you remove the external data entry loop and substitute the test array a = [4, 9, 2, 17, 3, 8] and N = 6 into the code, your code will work correctly.
In general, this is not a pythonic style. If for example:
min([mid for left, mid, right in zip(a, a[1:], a[2:]) if left > mid < right])
Source: https://ru.stackoverflow.com/questions/870382/
All Articles