[Tutor] Detect duplicate digits in a number
Alan Gauld
alan.gauld at yahoo.co.uk
Wed Feb 9 05:09:09 EST 2022
On 09/02/2022 01:39, Manprit Singh wrote:
> def detect_repeat(num):
> lx = []
> while num:
> num, rem = divmod(num, 10)
> if rem in lx:
> return False
> lx.append(rem)
> return True
I'd either rename the function to something like unique_digits()
or reverse the return values. If I saw code like
if detect_repeat(n):
# do_something()
I'd expect do_something to be called if there were repeat
digits. You function reverses the logic implied by the name.
> len(set(str(2343))) == len(str(2343))
> that also produces the desired result -False
>
> The second solution according to me lacks readability and again there are
> lots of conversion str, set and all .
You can reduce the number of conversions by just doing it once:
s = str(n)
len(s) == len(set(s))
If you are concerned about performance test it. Try your function
versus the str/set test(in another function) and see which is fastest.
Your functuon is doing a lot of work so I wouldn't be surprised if
it's actually slower than the str/set approach.
> Just need your opinion and guidance . In the first solution If you can see,
> there are two return statements . Is this practice considered ok ?
Computer Science purists will say no.
Pragmatic programmers will say yes, it's very common.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list