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 application in data domains. Let’s discuss certain ways in which this task can be performed.
Input : test_list = [4, 5, 4, 1, 7, 2, 5, 6, -2, -9, -10]
Output : 8
Input : test_list = [4, -5, -4, -1, -7, 2, 5, -6, -2, -9, -10]
Output : 2
Method #1 : Using loop
This is one of the way in which we perform this task. In this brute force way, we iterate for all the elements and keep on updating max, whenever the positive elements chain is broken.
The original list : [4, 5, -4, -1, -7, 2, 5, 6, -2, -9, -10] Maximum elements run length : 3
Method #2 : Using
groupby() + defaultDict() + max()
The combination of above functions can be used to solve this problem. In this, we perform the task of grouping using groupby(), we can perform the task of finding max of both negative and positive maximum run by grouping them against different keys, and using max() to find maximum of list at end.
The original list : [4, 5, -4, -1, -7, 2, 5, 6, -2, -9, -10] Maximum elements run length : 3 Maximum negative elements run length : 3
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course