a = [] b = 0 c = 0 d = 30 for i in range(0, d): a.append(int(input())) if a[i] < 0: b = b + 1 if a[i + 1] >= 0: if b > c: c = b b = 0 print(c) 

It is necessary to describe on Python an algorithm for counting the maximum number of consecutive negative elements in an integer array of length 30.

I wrote such a program above, but it gives an error in the line if a[i + 1] >= 0: I don’t understand why, because if you put minus instead of plus, then everything works

  • If the element a [i] is added to the array, because there is no next one yet, is it? And with -1 are features of indexing in Python - MBo
  • and how do I then compare the next element with zero? - Ivan
  • check current - splash58
  • OK. First enter the entire array, then process. - MBo pm
  • the assignment says that the program should work for any list, I realized my mistake, thanks a lot for the help - Ivan

2 answers 2

 import itertools my_list = [7, 6, -3, -3, -8, 2, -5, 4, -8, -2, -6, -1] is_negative = [True if num < 0 else False for num in my_list] groups = itertools.groupby(is_negative) occurrences_of_negatives = [len(list(g)) for k, g in groups if k] result = max(occurrences_of_negatives) 

Explanation:

First, create a new is_negative list to get only 2 categories :

  • True for negative numbers,
  • False for all others.

In our case, we get from the list my_list :

 [ 7, 6, -3, -3, -8, 2, -5, 4, -8, -2, -6, -1 ] 

such a list is_negative :

 [False, False, True, True, True, False, True, False, True, True, True, True]` 

Then, itertools.groupby() function itertools.groupby() we obtain from it groups of consecutive values — something like a dictionary, although this is not a dictionary — in our case

 {False: [False, False], True: [True, True, True], False: [False], True: [True], False: [False], True: [True, True, True, True]} 

From it we will build the list only for True keys , and we are only interested in the lengths of suitable lists. In our case, the occurrences_of_negatives list will be as follows:

 [3, 1, 4] 

And this is almost everything - the result will be the maximum value in this list.

  • It may be easier: is_negative = [num < 0 for num in my_list] - gil9red

Corrected algorithm from the question:

 items = [] number = 0 max_number = 0 max_arr_len = 5 for i in range(max_arr_len): x = int(input()) items.append(x) if x < 0: number += 1 if number > max_number: max_number = number else: number = 0 print(max_number) 

The same algorithm, but for processing the entire list:

 my_list = [7, 6, -3, -3, -8, 2, -5, 4, -8, -2, -6, -1] number = 0 max_number = 0 for x in my_list: if x < 0: number += 1 if number > max_number: max_number = number else: number = 0 print(max_number) # 4