Python – Fill gaps in consecutive Records
Last Updated :
27 Apr, 2023
Sometimes, while working with Python records, we can have a problem in which we have consecutive records, but a few missing and needs to be filled with any constant K. This kind of problem can have application in domains such as web development. Let’s discuss certain ways in which we need to perform this task.
Input : test_list = [(1, 4), (9, 11)] K = None
Output : [(1, 4), (2, None), (3, None), (4, None), (5, None), (6, None), (7, None), (8, None), (9, 11)]
Input : test_list = [(1, 4), (2, 11)] K = None
Output : [(1, 4), (2, 11)]
Method #1 : Using loop This is one way in which this problem can be solved. In this, we check at each iteration if the element exists, if no, then it is filled with required value, if yes, the original value is retained.
Python3
test_list = [( 1 , 4 ), ( 3 , 5 ), ( 4 , 6 ), ( 7 , 8 ), ( 9 , 11 )]
print ("The original list is : " + str (test_list))
K = "New"
res = []
cnt = 0
for i, j in test_list:
if i - cnt > 1 :
for k in range (cnt + 1 , i):
res.append((k, K))
res.append((i, j))
cnt = i
print ("The list after filling gaps : " + str (res))
|
Output :
The original list is : [(1, 4), (3, 5), (4, 6), (7, 8), (9, 11)] The list after filling gaps : [(1, 4), (2, ‘New’), (3, 5), (4, 6), (5, ‘New’), (6, ‘New’), (7, 8), (8, ‘New’), (9, 11)]
Time Complexity: O(n*n) where n is the number of elements in the list “test_list”. The loop is used to perform the task and it takes O(n*n) time.
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the list “test_list”.
Method #2 : Using min() + max() + dict() + list comprehension This is yet another way in which this problem can be solved. In this, we check the range using min() and max() and use dictionary as a container of getting values that is required to fill in.
Python3
test_list = [( 1 , 4 ), ( 3 , 5 ), ( 4 , 6 ), ( 7 , 8 ), ( 9 , 11 )]
print ("The original list is : " + str (test_list))
K = "New"
test_list = dict (test_list)
mini, maxi = min (test_list), max (test_list)
res = [(idx, test_list.get(idx)) for idx in range (mini, maxi + 1 )]
print ("The list after filling gaps : " + str (res))
|
Output :
The original list is : [(1, 4), (3, 5), (4, 6), (7, 8), (9, 11)] The list after filling gaps : [(1, 4), (2, ‘New’), (3, 5), (4, 6), (5, ‘New’), (6, ‘New’), (7, 8), (8, ‘New’), (9, 11)]
Time Complexity: O(n) where n is the number of elements in test_list.
Auxiliary Space: O(m), where m is length of res list.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...