-1

I am writing a function that returns the total count of digits(of an integer) that can divide the integer that it is a part of. For ex- Integer -111 count - 3 as all 1,1,1 divide 111 Integer - 103456 count - 2 only divisible by 1,4. To handle the special case of division by 0 , I have used if-else statements .However, I am still getting a zero divison error. Why am I still getting this error? My error message:-ZeroDivisionError:integer division or modulo by zero

My code-

    count=0
    divisors_list=[]
    number_in_string = str(n)
    divisors_list=list(number_in_string)
    for divisor in divisors_list:
       if divisor != 0:
            if n%int(divisor) == 0:
               count+=1
    return count

x=findDigits(103456)
yash471994
  • 63
  • 7

2 Answers2

1

int(divisor) can be 0 even if divisor != 0.

>>> divisor = 0.5
>>> int(divisor)
0

I would suggest to ask for forgiveness instead of permission and just catch the ZeroDivisionError.

try:
    if n%int(divisor) == 0:
        count += 1
except ZeroDivisionError:
    pass
timgeb
  • 76,762
  • 20
  • 123
  • 145
1

The issue is bad usage of strings as integers.

One way to fix your code is:

def findDigits(n):
    count = 0
    number_in_string = str(n)
    divisors_list = list(number_in_string)
    for divisor in divisors_list:
        # *** at this point, divisor is a string ***
        divisor = int(divisor)  # <== cast it to int
        if divisor != 0:
            if n % divisor == 0:
               count += 1
    return count
Roy2012
  • 11,755
  • 2
  • 22
  • 35