Python - Consecutive Ranges of K greater than N

PythonServer Side ProgrammingProgramming

When it is required to get the consecutive ranges of ‘K’ which are greater than ‘N’, the ‘enumerate’ attribute and simple iteration is used.

Example

Below is a demonstration of the same

my_list = [3, 65, 33, 23, 65, 65, 65, 65, 65, 65, 65, 3, 65]
print("The list is :")
print(my_list)
K = 65
N = 3
print("The value of K is ")
print(K)
print("The value of N is ")
print(N)
my_result = []
beg, end = 0, 0
previous = 1
for index, element in enumerate(my_list):
   if element == K:
      end = index

      if previous != K:
         beg = index
   else:

      if previous == K and end - beg + 1 >= N:
         my_result.append((beg, end))
   previous = element

print("The result is :")
print(my_result)

Output

The list is :
[3, 65, 33, 23, 65, 65, 65, 65, 65, 65, 65, 3, 65]
The value of K is
65
The value of N is
3
The result is :
[(4, 10)]

Explanation

  • A list is defined and is displayed on the console.

  • The values for ‘K’ and ‘N’ are defined and are displayed on the console.

  • An empty list is defined.

  • The value for ‘previous’ is defined.

  • The values for ‘beginning’ and ‘end’ are defined.

  • The list is iterated over by enumerating it.

  • If any element in the list is equivalent to another value ‘k’, the index value is redefined.

  • Otherwise, the values of ‘previous’ is redefined.

  • The beginning and end values are appended to the empty list.

  • This is returned as output.

  • The output is displayed on the console.

raja
Published on 21-Sep-2021 08:10:07
Advertisements