How to extract numbers with repeating digits within a range

Viewed 611

I need to identify the count of numbers with non-repeating digits in the range of two numbers. Suppose n1=11 and n2=15.

There is the number 11, which has repeated digits, but 12, 13, 14 and 15 have no repeated digits. So, the output is 4.

Wrote this code:

n1=int(input())
n2=int(input())

count=0

for i in range(n1,n2+1):
    lst=[]
    x=i
    while (n1>0):
        a=x%10
        lst.append(a)
        x=x//10
    for j in range(0,len(lst)-1):
      for k in range(j+1,len(lst)):
        if (lst[j]==lst[k]):
            break
        else:
            count=count+1
print (count)

While running the code and after inputting the two numbers, it does not run the code but still accepts input. What did I miss?

1 Answers

The reason your code doesn't run is because it gets stuck in your while loop, it can never exit that condition, since n1 > 0 will never have a chance to be evaluated as False, unless the input itself is <= 0.

Anyway, your approach is over complicated, not quite readable and not exactly pythonic. Here's a simpler, and more readable approach:

from collections import Counter

n1 = int(input())
n2 = int(input())

count = 0

for num in range(n1, n2+1):
    num = str(num)
    digit_count = Counter(num)
    has_repeating_digits = any((True for count in digit_count.values() if count > 1))

    if not has_repeating_digits:
        count += 1

print(count)

When writing code, in general you should try to avoid nesting too much stuff (in your original example you have 4 nested loops, that's readability and debugging nightmare), and try using self-describing variable names (so a, x, j, k, b... are kind of a no-go).

If in a IPython session you run import this you can also read the "Zen of Python", which kind of sums up the concept of writing proper pythonic code.

Related