logo CodeStepByStep logo


Language/Type: Python recursion recursive programming

Write a recursive function digit_match that accepts two non-negative integers as parameters and that returns the number of digits that match between them. Two digits match if they are equal and have the same position relative to the end of the number (i.e. starting with the ones digit). In other words, the function should compare the last digits of each number, the second-to-last digits of each number, the third-to-last digits of each number, and so forth, counting how many pairs match. For example, for the call of digit_match(1072503891, 62530841), the function would compare as follows:

1 0 7 2 5 0 3 8 9 1
    | | | | | | | |
    6 2 5 3 0 8 4 1

The function should return 4 in this case because 4 of these pairs match (2-2, 5-5, 8-8, and 1-1). Below are more examples:

Call Value Returned
digit_match(38, 34) 1
digit_match(5, 5552) 0
digit_match(892, 892) 3
digit_match(298892, 7892) 3
digit_match(380, 0) 1
digit_match(123456, 654321) 0
digit_match(1234567, 67) 2

Your function should raise a ValueError if either of the two parameters is negative. You are not allowed to construct any structured objects (no string, list, dictionary, etc.) and you may not use any loops to solve this problem; you must use recursion.

Function: Write a Python function as described, not a complete program.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.