Given a List of Integer Values Write a Python Program to Check Whether it Contains Same Number in Adjacent Position Display The Count of Such Adjacent Occurrences

Given a List of Integer Values Write a Python Program to Check Whether it Contains Same Number in Adjacent Position Display The Count of Such Adjacent Occurrences

Hi, in this blog lets try to count the adjacent occurrences of numbers in a list. Adjacent means in a list given a number, same number appears as its neighbor then adjacent count will be 1.

 

 

Python adjacent counter


 

 

For example:

Take this list of numbers [0, 2, 2, 3, 3] here the 2 is neighbor of 2 that is same number adjacent so the adjacent count will be 1. Again lets talk about 3 again 3 is neighbor of 3 so the adjacent count becomes 2. You have to print the output as 2.


Now lets try writing the program, take a list of numbers and use the for loop to traverse all index of the list until n-1, compare index item of list with index+1 that is next item of list, if they both are same increment the adjacent count. Once the for loop completes print the count


my_list = [1, 2, 3, 4, 5, 5, 5, 1, 1, 2, 2]
my_list = [1, 2, 3, 4, 5, 5, 5, 1, 1, 2, 2]

adjacent_count = 0
for index in range(len(my_list) - 1):
if my_list[index] == my_list[index + 1]:
adjacent_count += 1

print("Adjacent Count is : ", adjacent_count)
 
 

Similarly we can write this program using while loop, just you have to initialize the index then check if index is less than the length of the list in while loop condition. Until then the loop continues. Then check if list item is equal to its next list item if yes increment the adjacent count. You have to increment the index as well.

Finally print the adjacent count.

 
my_list = [1, 2, 3, 4, 5, 5, 5, 1, 1, 2, 2]

adjacent_count = 0
index = 0
while index < len(my_list)-1:
if my_list[index] == my_list[index + 1]:
adjacent_count += 1
index += 1

print("Adjacent Count is : ", adjacent_count)


OUTPUT : 

# python main.py

Adjacent Count is :  4


Post a Comment

0 Comments