简体   繁体   中英

How to create a function that finds number of divisible digits given two parameters

So I want to create a function that takes two ints: n and m. I want the function to return the number of digits in n that are divisible by m. A couple special cases, if one of the digits in n is 0 then it will count it as divisible. I am trying to do this by manipulating n itself but am not sure how to effectively loop through each number of the int to check if it is divisible by m. Here's what I have so far:

def divisible_nums(n, m):
    num_divisible = 0
    while n % 10 in range(1,10):
        last_digit = n % 10
        if last_digit / m == 0:
            num_divisible += 1
            n = n // 10
        else:
            n = n // 10
    return num_divisible

It just keeps returning 0, any ideas?

You have two problems.

  1. Your while condition is wrong. You'll stop as soon as you get to a 0 digit. It should be while n != 0: .
  2. Your test for the last digit being divisible by m is wrong, you have to use % , not / .
def divisible_nums(n, m):
    num_divisible = 0
    while n != 0:
        last_digit = n % 10
        if last_digit % m == 0:
            num_divisible += 1
        n = n // 10
    return num_divisible

Also, n = n // 10 is the same in both the if and else , so take it out of the condition and move it into the main body of the loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM