Python program to construct Equidigit tuples

Python program to construct Equidigit tuples

For instance, (23, 45, 12) is an equidigit tuple as all the numbers in the tuple have 2 digits, while (23, 45, 123) is not.

Let's create a Python program that constructs equidigit tuples from a given list of numbers:

Approach:

  1. Split the list into groups based on the number of digits.
  2. For each group, form tuples of numbers.
  3. Return the list of equidigit tuples.

Python Program:

from collections import defaultdict def equidigit_tuples(numbers): """Construct tuples of numbers with the same number of digits.""" # Group numbers by their number of digits digit_groups = defaultdict(list) for num in numbers: num_digits = len(str(num)) digit_groups[num_digits].append(num) # Form equidigit tuples result = [] for group in digit_groups.values(): result.extend([(group[i], group[j]) for i in range(len(group)) for j in range(i+1, len(group))]) return result # Testing the function numbers = [23, 45, 12, 123, 456, 789] print(f"Equidigit tuples: {equidigit_tuples(numbers)}") 

Output:

Equidigit tuples: [(23, 45), (23, 12), (45, 12), (123, 456), (123, 789), (456, 789)] 

Explanation:

  1. The function first groups numbers based on their number of digits using a dictionary (digit_groups). The number of digits is determined by converting the number to a string and getting its length.
  2. It then forms tuples from numbers in each group using nested loops. Here, we've created 2-tuple combinations, but the logic can be extended for larger tuples if needed.

With this program, you can easily identify and create tuples of numbers from a list that have the same number of digits.


More Tags

gnuplot python-asyncio indexoutofrangeexception owl-carousel x509certificate2 iasyncenumerable getattr openpyxl date-difference out

More Programming Guides

Other Guides

More Programming Examples