Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to construct Equidigit tuples
Equi-digit tuples are tuples where a number is split into two halves at the middle position. Python provides an efficient way to construct these using the floor division operator // and string slicing.
Understanding Equi-digit Tuples
An equi-digit tuple divides a number into two parts of equal or nearly equal length. For even-digit numbers, both parts have equal digits. For odd-digit numbers, the first part has one fewer digit than the second part.
Example
Below is a demonstration of constructing equi-digit tuples ?
my_list = [5613, 1223, 966143, 890, 65, 10221]
print("The list is :")
print(my_list)
my_result = []
for sub in my_list:
mid_index = len(str(sub)) // 2
element_1 = str(sub)[:mid_index]
element_2 = str(sub)[mid_index:]
my_result.append((int(element_1), int(element_2)))
print("The resultant list is :")
print(my_result)
The output of the above code is ?
The list is : [5613, 1223, 966143, 890, 65, 10221] The resultant list is : [(56, 13), (12, 23), (966, 143), (8, 90), (6, 5), (10, 221)]
How It Works
The algorithm follows these steps:
- Convert each number to a string to access individual digits
- Calculate the middle index using floor division
// - Split the string at the middle index using slicing
- Convert both parts back to integers and create a tuple
Alternative Implementation Using List Comprehension
Here's a more concise version using list comprehension ?
numbers = [5613, 1223, 966143, 890, 65, 10221]
result = [(int(str(num)[:len(str(num))//2]),
int(str(num)[len(str(num))//2:]))
for num in numbers]
print("Original numbers:", numbers)
print("Equi-digit tuples:", result)
Original numbers: [5613, 1223, 966143, 890, 65, 10221] Equi-digit tuples: [(56, 13), (12, 23), (966, 143), (8, 90), (6, 5), (10, 221)]
Conclusion
Equi-digit tuples split numbers into two parts using floor division and string slicing. This technique is useful for number manipulation and pattern analysis in Python programming.
