user11735387
user11735387

Reputation:

How would I find get the distinct digits of a number Python

I need to find all the distinct digits of a number and put them in an array, without looping.

I have already tried looping, but it is too slow.

If the number was 4884, then I would get [4,8] as an output.

Upvotes: 0

Views: 2129

Answers (3)

Akaisteph7
Akaisteph7

Reputation: 6476

You can use numpy unique:

num = 4884
res = np.unique(list(str(num))).astype(int)
print(res)

Output:

[4 8]


You can also do something like this:

list(dict(zip(map(int, list(str(num))), [0]*len(str(num)))).keys())

Not sure why you would want something so complicated. It is probably not faster than using set.


Some tests:

import timeit
>>> timeit.timeit('import numpy as np; np.unique(list(str(4884))).astype(int)', number=10000)
0.1892512352597464
timeit.timeit('set(map(int, str(4884)))', number=10000)
0.02349709570256664
timeit.timeit('map(int, list(dict.fromkeys(list(str(4884)))))', number=10000)
0.02554667675917699
timeit.timeit('list(dict(zip(map(int, list(str(4884))), [0]*len(str(4884)))).keys())', number=10000)
0.03316584026305236

Using set is definitely the fastest.

Upvotes: 0

Woobensky Pierre
Woobensky Pierre

Reputation: 66

use this technique

a = 658556
a = str(a)
mylist = list(dict.fromkeys(list(a)))
print(mylist)

output:

['6', '5', '8']

Upvotes: 0

Ram K
Ram K

Reputation: 1785

>>> r = set(map(int, str(4884))) 
>>> r
{8, 4}

Upvotes: 1

Related Questions