Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Minimum of two numbers in Python
Next article icon

Python – Find minimum of non zero groups

Last Updated : 02 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Many times we need to get the minimum of not the whole list but just a part of it and at regular intervals. These intervals are sometimes decided statically before traversal, but sometimes, the constraint is more dynamic and hence we require to handle it in more complex way. Criteria discussed here is minimum of non-zero groups. Let’s discuss certain ways in which this task can be done. 

Method #1 : Using loops This task can be performed using the brute force manner using the loops. We just traverse the list each element to test for it’s succeeding element to be non-zero value and perform the minimum once we find a next value to be zero and append it in result list. 

Python3




# Python3 code to demonstrate
# Natural Numbers Minimum
# Using loops
 
# initializing list
test_list = [4, 9, 0, 0, 3, 4, 5, 0, 0, 4, 0]
 
# printing original list
print("The original list : " + str(test_list))
 
# using loops
# Natural Numbers Minimum
res = []
val = 99999
for ele in test_list:
    if ele == 0:
        if val != 99999:
            res.append(val)
            val = 99999
    else:
        val = min(val, ele)
 
# print result
print("The non-zero group Minimum of list is : " + str(res))
 
 
Output : 
The original list : [4, 9, 0, 0, 3, 4, 5, 0, 0, 4, 0] The non-zero group Minimum of list is : [4, 3, 4]

Method #2: Using itertools.groupby() + min() This particular task can also be performed using groupby function to group all the non-zero values and min function can be used to perform their minimum. 

Python3




# Python3 code to demonstrate
# Natural Numbers Minimum
# Using itertools.groupby() + min()
from itertools import groupby
 
# initializing list
test_list = [4, 9, 0, 0, 3, 4, 5, 0, 0, 4, 0]
 
# printing original list
print("The original list : " + str(test_list))
 
# using itertools.groupby() + min()
# Natural Numbers Minimum
res = [min(val) for keys, val in groupby(test_list, key = lambda x: x != 0) if keys != 0]
 
# print result
print("The non-zero group minimum of list is : " + str(res))
 
 
Output : 
The original list : [4, 9, 0, 0, 3, 4, 5, 0, 0, 4, 0] The non-zero group Minimum of list is : [4, 3, 4]

Method #3: Using a list comprehension to find non-zero groups:

Step-by-step approach:

  • Convert the list of integers to a string: O(n)
  • Use str.join to concatenate the elements of the list into a single string: O(n)
  • Use str.split to split the string at every occurrence of ‘0’: O(n)
  • Filter out any empty groups: O(n)
  • Convert each group back to a list of integers: O(n)
  • Use a list comprehension to find the minimum value in each group: O(n)
  • Return the list of minimum values: O(n)

Python3




def min_nonzero_groups_3(lst):
    groups = [list(group) for group in ''.join(map(str, lst)).split('0') if group]
    return [min(group) for group in groups]
 
# Example usage:
lst = [4, 9, 0, 0, 3, 4, 5, 0, 0, 4, 0]
print(min_nonzero_groups_3(lst))  # Output: [4, 3, 4]
 
 
Output
['4', '3', '4']

Time complexity: O(n)
Auxiliary space: O(n)

Method 4: Using the numpy library. 

Step-by-step approach:

  • Import the numpy library.
  • Convert the given list into a numpy array.
  • Get the indices of non-zero elements in the array.
  • Get the indices where consecutive elements differ by 1 (i.e., indices of the end of each non-zero group).
  • Get the start and end indices of each non-zero group by adding the first and last indices.
  • Using a list comprehension, calculate the minimum value for each group.
  • Print the result.

Python3




# Python3 code to demonstrate
# Natural Numbers Minimum
# Using numpy
 
import numpy as np
 
# initializing list
test_list = [4, 9, 0, 0, 3, 4, 5, 0, 0, 4, 0]
 
# converting list to numpy array
arr = np.array(test_list)
 
# getting indices of non-zero elements
indices = np.nonzero(arr)[0]
 
# getting indices where consecutive elements differ by 1
diff_indices = np.where(np.diff(indices) != 1)[0]
 
# adding first and last indices
start_indices = np.append(indices[0], indices[diff_indices + 1])
end_indices = np.append(indices[diff_indices], indices[-1])
 
# getting minimum values for each group
min_vals = np.array([np.min(arr[start:end+1]) for start, end in zip(start_indices, end_indices)])
 
# print result
print("The non-zero group minimum of list is : " + str(list(min_vals)))
 
 

Output:

 The non-zero group minimum of list is : [4, 3, 4]

Time complexity: O(n), where n is the length of the input list, because we are performing a constant number of operations for each non-zero group.
Auxiliary space: O(n), where n is the length of the input list, because we are storing the indices of non-zero elements and the start and end indices of each non-zero group.



Next Article
Minimum of two numbers in Python
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • Minimum of two numbers in Python
    In this article, we will explore various methods to find minimum of two numbers in Python. The simplest way to find minimum of two numbers in Python is by using built-in min() function. [GFGTABS] Python a = 7 b = 3 print(min(a, b)) [/GFGTABS]Output3 Explanation: min() function compares the two numbe
    2 min read
  • Python | List of tuples Minimum
    Sometimes, while working with Python records, we can have a problem in which we need to perform cross minimum of list of tuples. This kind of application is popular in web development domain. Let’s discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + zip()
    4 min read
  • Python | Minimum K records of Nth index in tuple list
    Sometimes, while working with data, we can have a problem in which we need to get the minimum of elements filtered by the Nth element of record. This has a very important utility in web development domain. Let’s discuss certain ways in which this task can be performed. Method #1 : Using filter() + l
    9 min read
  • Python - Find minimum k records from tuple list
    Sometimes, while working with data, we can have a problem in which we have records and we require to find the lowest K scores from it. This kind of application is popular in web development domain. Let’s discuss certain ways in which this problem can be solved. Method #1 : Using sorted() + lambda Th
    6 min read
  • Python - Find Minimum Pair Sum in list
    Sometimes, we need to find the specific problem of getting the pair which yields the minimum sum, this can be computed by getting initial two elements after sorting. But in some case, we don’t with to change the ordering of list and perform some operation in the similar list without using extra spac
    4 min read
  • Python Program for Find minimum sum of factors of number
    Given a number, find minimum sum of its factors.Examples: Input : 12Output : 7Explanation: Following are different ways to factorize 12 andsum of factors in different ways.12 = 12 * 1 = 12 + 1 = 1312 = 2 * 6 = 2 + 6 = 812 = 3 * 4 = 3 + 4 = 712 = 2 * 2 * 3 = 2 + 2 + 3 = 7Therefore minimum sum is 7Inp
    1 min read
  • Python - Minimum Product Pair in List
    Sometimes, we need to find the specific problem of getting the pair that yields the minimum product, this can be solved by sorting and getting the first and second elements of the list. But in some case, we don’t with to change the ordering of list and perform some operation in the similar list with
    3 min read
  • Python | Find groups of strictly increasing numbers in a list
    Given a list of integers, write a Python program to find groups of strictly increasing numbers. Examples: Input : [1, 2, 3, 5, 6] Output : [[1, 2, 3], [5, 6]] Input : [8, 9, 10, 7, 8, 1, 2, 3] Output : [[8, 9, 10], [7, 8], [1, 2, 3]] Approach #1 : Pythonic naive This is a naive approach which uses a
    5 min read
  • Python - Row with Minimum Sum in Matrix
    We can have an application for finding the lists with the minimum value and print it. This seems quite an easy task and may also be easy to code, but having shorthands to perform the same are always helpful as this kind of problem can come in web development. Method #1 : Using reduce() + lambda The
    4 min read
  • Python Program for Maximum difference between groups of size two
    Given an array of even number of elements, form groups of 2 using these array elements such that the difference between the group with highest sum and the one with lowest sum is maximum.Note: An element can be a part of one group only and it has to be a part of at least 1 group. Examples: Input : ar
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences