Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
154 views
in Technique[技术] by (71.8m points)

python - Not getting the correct output on a function that returns the number of digits divisible by another

I'm currently writing a function that is supposed to take two integers (n and m) as arguments and then return the number of digits in n that are divisible by m. (If a digit is 0, it is divisible by any number)

An example of this could be (650899, 3) (n, m) and the answer is 4 (because 0, 6, and 9, are all divisible by 3).

I'm getting the correct output for some values that I put through the function, but not all of them. Can anyone see my error here? I also want to be able to put negative values of n through the function and have it give me a result.

Here's my code so far:

def divisible_digits(n, m):
    count = 0
    for i in range(n, m):
        if (i % m == 0):
            count += 1
    return count
question from:https://stackoverflow.com/questions/65838298/not-getting-the-correct-output-on-a-function-that-returns-the-number-of-digits-d

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This should help you:

def diviisble_digits(n, m):
    sn = str(n)
    return sum(1 for d in sn if int(d)%m == 0)

diviisble_digits(n, m)  # n, m = 650899, 3
4

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...