[Tutor] Detect duplicate digits in a number

Joel Goldstick joel.goldstick at gmail.com
Tue Feb 8 20:46:13 EST 2022


On Tue, Feb 8, 2022 at 8:39 PM Manprit Singh <manpritsinghece at gmail.com> wrote:
>
> Dear Sir,
>
> I have to produce a result False if a number contains repeating digits and
> True if the number do not have any repeating digit:
>
> Example :
> if number is 2343 the result produced must be False
> if number is 235 the result produced must be True
>
> I have tried to implement it in  the following ways:
> 1) Using user defined function
>
> def detect_repeat(num):
>     lx = []
>     while num:
>         num, rem = divmod(num, 10)
>         if rem  in lx:
>             return False
>         lx.append(rem)
>     return True
>
> ans = detect_repeat(2343)
> print(ans)   # Results in False that is the desired result
>
> 2) Using str, set, len
>
> 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 .
> The  first solution, I feel , is good.
>
> Just need your opinion and guidance . In the first solution If you can see,
> there are two return statements . Is this practice considered ok ?
>
> Regards
> Manprit Singh
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor

You can convert your number to a string.  Then convert the string to a
list of characters.  Then convert the list to a set.  If the length of
the set is different than the length of the list, you have repeated
digits:

>>> n = 12341
>>> s = str(n)
>>> s
'12341'
>>> l = list(s)
>>> l
['1', '2', '3', '4', '1']
>>> s = set(l)
>>> s
{'4', '2', '3', '1'}
>>> len(s)
4
>>> len(l)
5
>>>


-- 
Joel Goldstick


More information about the Tutor mailing list