Skip to content Skip to sidebar Skip to footer

How Do I Return The Number Of Unique Digits In A Positive Integer

Example: unique_dig(123456) All unique 6 I'm trying to write code to have a function return how many unique numbers there are in a positive integer. count = 0 for i in unique_digi

Solution 1:

Convert the integer to a string, convert that string to a set of characters, then get the size of the set.

>>> N = 12334456
>>> len(set(str(N)))
6

I am indebted to Stefan Pochmann for teaching me something. (See the comments.)


Solution 2:

Here is a solution in pseudocode. You should be able to convert this into Python without too much trouble. Depending on the limitations (I assume this is homework of some kind), you may need to nest a second loop to check each char against the arrayOfUniqueCharacters.

someInputString = "abracadabra"
emptyArrayOfUniqueCharacters = []

FOR char IN someInputString
    IF char NOT IN arrayOfUniqueChars
        APPEND char TO arrayOfUniqueChars
RETURN length OF arrayOfUniqueChars

Post a Comment for "How Do I Return The Number Of Unique Digits In A Positive Integer"