Skip to content
Related Articles

Related Articles

Python – Remove numbers with repeating digits

View Discussion
Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 24 Aug, 2022
View Discussion
Improve Article
Save Article

Given a list of numbers, the task is to write a Python program to remove all numbers with repetitive digits.

Examples:

Input : test_list = [4252, 6578, 3421, 6545, 6676]
Output : test_list = [6578, 3421]
Explanation : 4252 has 2 occurrences of 2 hence removed. Similar case for all other removed.

Input : test_list = [4252, 6578, 3423, 6545, 6676]
Output : test_list = [6578]
Explanation : 4252 has 2 occurrences of 2 hence removed. Similar case for all other removed.

Method 1 : Using set() + len() + list comprehension

In this, we perform the task of eliminating repeating elements using set() and then compare the length to be equal to the original length. If found, True is returned, else False is returned.

Python3




# Python3 code to demonstrate working of
# Remove numbers with repeating digits
# Using set() + len() + list comprehension
 
# initializing list
test_list = [4252, 6578, 3421, 6545, 6676]
 
# printing original list
print("The original list is : " + str(test_list))
 
# set() used to remove digits
res = [sub for sub in test_list if len(set(str(sub))) == len(str(sub))]
 
# printing result
print("List after removing repeating digit numbers : " + str(res))


Output

The original list is : [4252, 6578, 3421, 6545, 6676]
List after removing repeating digit numbers : [6578, 3421]

Time Complexity: O(n)
Auxiliary Space: O(n)

Method 2 : Using regex()

Appropriate regex can also be used for the task of checking for each digit repetition only once.

Python3




# Python3 code to demonstrate working of
# Remove numbers with repeating digits
# Using regex()
import re
 
# initializing list
test_list = [4252, 6578, 3421, 6545, 6676]
 
# printing original list
print("The original list is : " + str(test_list))
 
# regex used to remove elements with repeating digits
regex = re.compile(r"(\d).*\1")
res = [sub for sub in test_list if not regex.search(str(sub))]
 
# printing result
print("List after removing repeating digit numbers : " + str(res))


Output

The original list is : [4252, 6578, 3421, 6545, 6676]
List after removing repeating digit numbers : [6578, 3421]

Time Complexity: O(n)
Auxiliary Space: O(n)


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!