[Tutor] Detect duplicate digits in a number

Alex Kleider alexkleider at gmail.com
Tue Feb 8 21:16:16 EST 2022


I'd suggest using sets.
turn each number into a string:
>>> s = str(n)
# create a set of characters in the string thus eliminating duplicates:
>>> myset = {c for c in s}
>>> if len(myset) == len(s):  # if the lengths are the same- there weren't
any duplicates
           print("there are no duplicates")
       else:  # there were duplicates
          print("duplicates were present")

On Tue, Feb 8, 2022 at 5:40 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
>


More information about the Tutor mailing list