Python Program to check if elements to the left and right of the pivot are smaller or greater respectively


Generally, pivot table is the table which contains the grouped values formed by aggregating the individual elements within one or more discrete categories.

In Python, the term "pivot" is often associated with sorting algorithms or operations that involve rearranging elements based on a specific value or condition. The pivot can be any element or position within the data structure, and its purpose is to divide the data into two parts: elements smaller than the pivot and elements greater than the pivot.

There are different ways to check if the elements to the left and right of the pivot are smaller or greater respectively.

Using loop s

Loops are used to iterate the elements as per the user requirement. Here in this article for loop is used to iterate the elements of the given array and checks for the smaller or greater element of the pivot.

Example

In this example we create for loop to iterate the elements of the array and create the condition to check for smaller or greater elements on left and right of the pivot.

def check_pivot(arr, pivot_index):
   pivot = arr[pivot_index]
   for i in range(pivot_index):
      if arr[i] >= pivot:
         return False
   for i in range(pivot_index + 1, len(arr)):
      if arr[i] <= pivot:
         return False
   return True
my_list = [1, 2, 3, 4, 5]
pivot_index = 2
if check_pivot(my_list, pivot_index):
   print("Elements to the left are smaller and to the right are greater.")
else:
   print("Elements to the left are not smaller and to the right are not greater.")

Output

Elements to the left are smaller and to the right are greater.

Using list slicing

List slicing is the technique which divides the list into different parts. Here in this article we will divide the given array into different parts and checks whether the elements are greater or smaller of the pivot.

Example

Here in this example we are slicing the given input array into different parts and check if the elements on right or left of the pivot are greater or smaller.

def check_pivot(arr, pivot_index):
   left = arr[:pivot_index]
   right = arr[pivot_index + 1:]
   return all(x < arr[pivot_index] for x in left) and all(x > arr[pivot_index] for x in right)
my_list = [1, 3, 3, 4, 5]
pivot_index = 2
if check_pivot(my_list, pivot_index):
    print("Elements to the left are smaller and to the right are greater.")
else:
    print("Elements to the left are not smaller and to the right are not greater.")

Output

Elements to the left are not smaller and to the right are not greater.

Updated on: 19-Oct-2023

30 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements