5 Best Ways to Find Tuples with All Elements Divisible by K in Python

Rate this post

πŸ’‘ Problem Formulation: The task is to write a Python program to identify and return tuples from a list where each element in the tuple is divisible by a specified integer k. For example, given a list of tuples [(2, 4, 6), (3, 6, 9), (4, 5, 8)] and a divisibility test integer k = 3, the desired output would be [(3, 6, 9)] as all elements in this tuple are divisible by 3.

Method 1: Using a Loop and all() Function

This approach involves iterating over each tuple in the list and checking if all elements are divisible by k using the built-in all() function. It’s straight-forward and easy to understand.

Here’s an example:

lst = [(2, 4, 6), (3, 6, 9), (4, 5, 8)]
k = 3
result = [tup for tup in lst if all(x % k == 0 for x in tup)]
print(result)

Output: [(3, 6, 9)]

This code defines a list of tuples lst and a divisor k. A list comprehension checks each tuple: if all elements are divisible by k (using a generator expression passed to all()), it includes the tuple in the result.

Method 2: Using Filter and Lambda Function

Filter method coupled with a lambda function can also be used to select the appropriate tuples. The filter() function returns an iterator yielding those items of the iterable for which function(item) is true.

Here’s an example:

lst = [(2, 4, 6), (3, 6, 9), (4, 5, 8)]
k = 3
result = list(filter(lambda tup: all(x % k == 0 for x in tup), lst))
print(result)

Output: [(3, 6, 9)]

A lambda function is defined within the filter() to implement the divisibility check. The filter() then applies this condition to each tuple in lst, and list() is used to convert the result back to a list.

Method 3: Using Nested Loops

For those preferring explicit control flow, nested loops can be used to iterate over each element in each tuple for the divisibility check. It is the most straightforward method but less Pythonic.

Here’s an example:

lst = [(2, 4, 6), (3, 6, 9), (4, 5, 8)]
k = 3
result = []
for tup in lst:
    if all(x % k == 0 for x in tup):
        result.append(tup)
print(result)

Output: [(3, 6, 9)]

In this snippet, explicit for-loops traverse each tuple and check the divisibility condition before appending the tuple to the result list.

Method 4: Using NumPy Library

For those working with numerical computations and high-performance requirements, NumPy’s array operations could be used for efficient processing.

Here’s an example:

import numpy as np
lst = [(2, 4, 6), (3, 6, 9), (4, 5, 8)]
k = 3
arrays = np.array(lst)
result = arrays[np.all(arrays % k == 0, axis=1)]
print(result)

Output: [[3 6 9]]

The snippet starts by importing NumPy and converting our list of tuples into a NumPy array. Then, boolean indexing is used along with np.all() to select only those rows where all elements meet the condition.

Bonus One-Liner Method 5: Using Comprehensions and Reduce

For a more functional programming approach, the reduce() function can be used alongside a list comprehension for an elegant one-liner.

Here’s an example:

from functools import reduce
lst = [(2, 4, 6), (3, 6, 9), (4, 5, 8)]
k = 3
result = [tup for tup in lst if reduce(lambda a, b: a and b, (x % k == 0 for x in tup))]
print(result)

Output: [(3, 6, 9)]

This snippet leverages functools.reduce() to apply a cumulated logical AND across the generator expression checking each element’s divisibility, compacted in a list comprehension.

Summary/Discussion

  • Method 1: Loop with all(). Strengths: Easy to understand, concise. Weaknesses: Not as compact as other one-liners.
  • Method 2: Filter with Lambda. Strengths: Functional programming style, clear intent. Weaknesses: Might be less intuitive, especially for beginners.
  • Method 3: Nested Loops. Strengths: Simple and explicit. Weaknesses: Verbosity, potential performance issues for large datasets.
  • Method 4: NumPy Library. Strengths: Speed and efficiency with large datasets. Weaknesses: Additional dependency, may be overkill for small tasks.
  • Method 5: Comprehensions and Reduce. Strengths: Functional and elegant. Weaknesses: Readability may suffer for those not familiar with functional programming concepts.