Python - Test Consecutive Element Matrix
Last Updated :
03 Jun, 2023
Given a Matrix, test if it is made of consecutive elements.
Input : test_list = [[4, 5, 6], [7], [8, 9, 10], [11, 12]]
Output : True
Explanation : Elements in Matrix range from 4 to 12.
Input : test_list = [[4, 5, 6], [7], [8, 18, 10], [11, 12]]
Output : False
Explanation : Elements not consecutive and not in a range.
Method #1: Using loop
In this, we check for consecution within the row, and before each row, check for 1st element to be next to last element from previous row.
Python3
# Python3 code to demonstrate working of
# Test Consecutive Element Matrix
# Using loop
# initializing list
test_list = [[4, 5, 6], [7], [8, 9, 10], [11, 12]]
# printing original list
print("The original list is : " + str(test_list))
res = True
mem_list = []
for sub in test_list:
flag = True
for ele in sub:
# checking for last element to be Consecutive
if len(mem_list) != 0:
if mem_list[-1] != ele - 1:
flag = False
break
mem_list.append(ele)
if not flag:
res = False
break
# printing result
print("Is Matrix Consecutive ? : " + str(res))
OutputThe original list is : [[4, 5, 6], [7], [8, 9, 10], [11, 12]]
Is Matrix Consecutive ? : True
Time Complexity: O(n*m)
Auxiliary Space: O(k)
Method #2 : Using chain.from_iterable() + all()
In this, we flatten matrix to list, and then check for all elements in consecution using all(), to be 1 greater than the preceding element in flattened Matrix.
Python3
# Python3 code to demonstrate working of
# Test Consecutive Element Matrix
# Using chain.from_iterable() + all()
from itertools import chain
# initializing list
test_list = [[4, 5, 6], [7], [8, 9, 10], [11, 12]]
# printing original list
print("The original list is : " + str(test_list))
# flattening matrix
test_list = list(chain.from_iterable(test_list))
# checking for boolean true
res = all(test_list[idx - 1] == test_list[idx] -
1 for idx in range(1, len(test_list)))
# printing result
print("Is Matrix Consecutive ? : " + str(res))
OutputThe original list is : [[4, 5, 6], [7], [8, 9, 10], [11, 12]]
Is Matrix Consecutive ? : True
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #3 : Using extend(),min(),max() and range() methods
Python3
# Python3 code to demonstrate working of
# Test Consecutive Element Matrix
# Using loop
# initializing list
test_list = [[4, 5, 6], [7], [8, 9, 10], [11, 12]]
# printing original list
print("The original list is : " + str(test_list))
res = False
x=[]
for i in test_list:
x.extend(i)
a=min(x)
b=max(x)
y=list(range(a,b+1))
if(x==y):
res=True
# printing result
print("Is Matrix Consecutive ? : " + str(res))
OutputThe original list is : [[4, 5, 6], [7], [8, 9, 10], [11, 12]]
Is Matrix Consecutive ? : True
Time Complexity: O(n^2), where n is the number of sublists in the list.
Auxiliary Space: O(n), as extra space is required of size n.
Method #4: Using set and range()
- Initialize a set to store all the unique elements from the nested list
- Iterate through each list in the nested list and update the set with its elements
- Check if the length of the set is equal to the difference between the maximum and minimum element in the set plus 1 (since we want to check for consecutive elements)
- If the condition is true, set res to True, else set it to False
- Print the final result
Python3
# Python3 code to demonstrate working of
# Test Consecutive Element Matrix
# Using set and range()
# initializing list
test_list = [[4, 5, 6], [7], [8, 9, 10], [11, 12]]
# printing original list
print("The original list is : " + str(test_list))
# using set and range()
elements_set = set()
for sublist in test_list:
elements_set.update(sublist)
if len(elements_set) == max(elements_set) - min(elements_set) + 1:
res = True
else:
res = False
# printing result
print("Is Matrix Consecutive ? : " + str(res))
OutputThe original list is : [[4, 5, 6], [7], [8, 9, 10], [11, 12]]
Is Matrix Consecutive ? : True
Time complexity: O(nlogn) - iterating through the nested list takes O(n) time and checking for consecutive elements in the set takes O(nlogn) time due to the set being sorted internally.
Auxiliary space: O(n) - storing all the unique elements in the set.
Method #5: Using numpy.diff() function
- Import the numpy package as np to use its functions.
- Create a nested list test_list containing multiple sublists of integers.
- Print the original list using the print statement and the str() function to convert the list to a string.
- Set the variable res to True.
- Loop through each sublist in the test_list using the for loop.
- Use the numpy diff() function to calculate the difference between adjacent elements in the current sublist. This returns a new array with one less element than the original sublist.
- Use the numpy all() function to check if all the elements in the resulting array are equal to 1. If yes, continue to the next sublist. If not, set res to False and break out of the loop.
- Print the final result using the print statement and the str() function to convert the boolean value to a string.
Python3
import numpy as np
# initializing list
test_list = [[4, 5, 6], [7], [8, 9, 10], [11, 12]]
# printing original list
print("The original list is : " + str(test_list))
res = True
for sub in test_list:
if np.all(np.diff(sub) == 1):
continue
else:
res = False
break
# printing result
print("Is Matrix Consecutive ? : " + str(res))
OUTPUT :
The original list is : [[4, 5, 6], [7], [8, 9, 10], [11, 12]]
Is Matrix Consecutive ? : True
Time complexity: O(nm) where n is the number of sublists in the input list and m is the maximum number of elements in a sublist.
Auxiliary space: O(m) where m is the maximum number of elements in a sublist.
Method 6 : using a list comprehension
- Initialize the test_list with the given values: test_list = [[4, 5, 6], [7], [8, 9, 10], [11, 12]].
- Initialize the variable res as True. This variable will store the result of whether the matrix is consecutive or not.
- Iterate over each sublist in the test_list using the outer loop for i in range(len(test_list)).
- For each sublist, iterate over its elements using the inner loop for j in range(len(test_list[i]) - 1).
- Inside the loop, check if the consecutive elements condition is satisfied by comparing the difference between the current element and the next element in the sublist with 1: test_list[i][j + 1] - test_list[i][j] == 1.
- If the condition is satisfied for all elements in all sublists, the matrix is consecutive. If any sublist has non-consecutive elements, set res to False and break out of the loop.
- After the loops, res will hold the result of whether the matrix is consecutive or not.
- Print the result by converting res to a string: print("Is Matrix Consecutive? : " + str(res)).
Python3
test_list = [[4, 5, 6], [7], [8, 9, 10], [11, 12]]
res = all(test_list[i][j + 1] - test_list[i][j] == 1
for i in range(len(test_list))
for j in range(len(test_list[i]) - 1))
print("Is Matrix Consecutive? : " + str(res))
OutputIs Matrix Consecutive? : True
Time complexity: O(n), where n is the total number of elements in the input list.
Auxiliary space: O(1)
Similar Reads
Python - Filter consecutive elements Tuples
Given a Tuple list, filter tuples that are made from consecutive elements, i.e diff is 1. Input : test_list = [(3, 4, 5, 6), (5, 6, 7, 2), (1, 2, 4), (6, 4, 6, 3)] Output : [(3, 4, 5, 6)] Explanation : Only 1 tuple adheres to condition. Input : test_list = [(3, 4, 5, 6), (5, 6, 7, 2), (1, 2, 3), (6,
5 min read
Python | Retain K consecutive elements
Sometimes while working with data, we can have a problem in which we need to select some of the elements that occur K times consecutively. This problem can occur in many domains. Let's discuss certain ways in which this problem can be solved. Method #1 : Using groupby() + list comprehension This t
8 min read
Python - Reorder for consecutive elements
Given a List perform reordering to get similar elements in consecution. Input : test_list = [4, 7, 5, 4, 1, 4, 1, 6, 7, 5] Output : [4, 4, 4, 7, 7, 5, 5, 1, 1, 6] Explanation : All similar elements are assigned to be consecutive. Input : test_list = [4, 7, 5, 1, 4, 1, 6, 7, 5] Output : [4, 4, 7, 7,
4 min read
Python - Remove Consecutive K element records
Sometimes, while working with Python records, we can have a problem in which we need to remove records on the basis of presence of consecutive K elements in tuple. This kind of problem is peculiar but can have applications in data domains. Let's discuss certain ways in which this task can be perform
7 min read
Python | Group consecutive list elements with tolerance
Sometimes, we might need to group list according to the consecutive elements in the list. But a useful variation of this can also be a case in which we need to consider a tolerance level, i.e allowing a skip value between numbers and not being exactly consecutive but a "gap" is allowed between numbe
3 min read
Python - Element wise Matrix Difference
Given two Matrixes, the task is to write a Python program to perform element-wise difference. Examples: Input : test_list1 = [[2, 4, 5], [5, 4, 2], [1, 2, 3]], test_list2 = [[6, 4, 6], [9, 6, 3], [7, 5, 4]] Output : [[4, 0, 1], [4, 2, 1], [6, 3, 1]] Explanation : 6 - 2 = 4, 4 - 4 = 0, 6 - 5 = 1. And
3 min read
Python - Similar Consecutive elements frequency
Sometimes, while working with Python, we can have a problem in which we have to find the occurrences of elements that are present consecutively. This problem have usage in school programming and data engineering. Let's discuss certain ways in which this task can be performed. Method #1 : Using loop
5 min read
Python - Consecutive identical elements count
Given the elements list, get all the elements that have an identical element as the next element. Input : test_list = [4, 5, 5, 5, 5, 6, 6, 7, 8, 2, 2, 10] Output : 3 Explanation : 5, 6 and 2 has identical element as their next element. Input : test_list = [4, 5, 5, 5, 5, 6, 6, 7, 8, 2, 3, 10] Outpu
5 min read
Python - Maximum length consecutive positive elements
Sometimes, while working with Python lists, we can have a problem in which we monitor a sequence and we need to find what was the maximum length when just positive elements occur. This kind of problem can have applications in data domains. Let's discuss certain ways in which this task can be perform
4 min read
Python - K difference Consecutive elements
Given a list of integer elements, check for each element if its difference with successive element is K. Input : test_list = [5, 6, 3, 2, 5, 3, 4], K = 1 Output : [True, False, True, False, False, True] Explanation : 5, 6; 3, 2; and 3, 4 have 1 diff. between them. Input : test_list = [5, 6, 3, 2, 5,
4 min read