You have a list of numbers and you want to filter out those numbers that contain unique digits, i.e. each digit may only occur once in the number.
Positive examples:
Negative examples:
How would you do that? My own idea is to convert each number to a string and then check whether the size of the set made out of the string's characters is equal to the length of the string. Something like that:
def uniques(numbers):
for number in numbers:
str_number = str(number)
if len(set(str_number)) == len(str_number):
yield number
for i in uniques(xrange(1000, 1050)):
print i
1023
1024
1025
1026
1027
1028
1029
1032
1034
1035
1036
1037
1038
1039
1042
1043
1045
1046
1047
1048
1049
Is there a way to do it without converting the integers to strings first?
Given a range, print all numbers having unique digits. Approach: As the problem is pretty simple, the only thing to be done is :- 1- Find the digits one by one and keep marking visited digits. 2- If all digits occurs one time only then print that number.
To get unique digits in a given number in Python, convert the given number to string, and pass this string to set() method. set() method returns a Python Set containing unique digits.
Example: C++ isdigit() for (int i = 0; i < strlen(str); i++) { ... } In other words, the loop iterates through the whole string since strlen() gives the length of str . In each iteration of the loop, we use the isdigit() function to check if the string element str[i] is a digit or not.
Using collections.Counter:
from collections import Counter
def unique(seq):
return any(x > 1 for x in Counter(seq).values())
This will work for any sequence, not only strings.
And only now I noticed that you didn't want to convert to strings... not sure why, but I'll let the answer stay.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With