Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter numbers that contain unique digits?

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:

  • 985
  • 58293.6
  • 0.1246

Negative examples:

  • 9585 (5 occurs twice)
  • 58293.666 (6 occurs three times)
  • 0.12461 (1 occurs twice)

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?

like image 535
pemistahl Avatar asked Jan 14 '13 10:01

pemistahl


People also ask

How do you check if a number has all unique digits?

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.

How do you find unique digits in a number in Python?

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.

How do you check if a number contains a certain digit in CPP?

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.


1 Answers

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.

like image 117
viraptor Avatar answered Oct 06 '22 16:10

viraptor