
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Group Integers in Python
Suppose we have a list of numbers called nums, we have to check whether we can split the list into 1 or more groups such that: 1. Size of each group is greater than or equal to 2. 2. Sizes of all groups are same. 3. All the numbers present in each group are the same.
So, if the input is like [3, 4, 6, 9, 4, 3, 6, 9], then the output will be True.
To solve this, we will follow these steps −
- counts := a map where each key are distinct element and values are their frequencies
- temp := 0
- for each count in counts, do
- if temp is same as 0, then
- temp := counts[count]
- otherwise,
- temp := gcd of counts[count] and temp
- if temp is same as 1, then
- return False
- if temp is same as 0, then
- return True
Let us see the following implementation to get better understanding −
Example
from collections import Counter import math class Solution: def solve(self, nums): counts = Counter(nums) temp = 0 for count in counts: if temp == 0: temp = counts[count] else: temp = math.gcd(counts[count], temp) if temp == 1: return False return True ob = Solution() L = [3, 4, 6, 9, 4, 3, 6, 9] print(ob.solve(L))
Input
[3, 4, 6, 9, 4, 3, 6, 9]
Output
True
- Related Articles
- Powerful Integers in Python
- Group Anagrams in Python
- Sum of Two Integers in Python
- Program to distribute repeating integers in Python
- Python – Filter Tuples with Integers
- Python - Group contiguous strings in List
- Convert number to list of integers in Python
- Converting all strings in list to integers in Python
- Access to the Group Database in Python
- Group-by and Sum in Python Pandas
- How can we read inputs as integers in Python?
- How do I specify hexadecimal and octal integers in Python?
- Python Group Anagrams from given list
- Python – Group Consecutive elements by Sign
- Python - Filter out integers from float numpy array

Advertisements