Checking to see if a number is evenly divisible by other numbers with recursion in Python

Posted by Ernesto on Stack Overflow See other posts from Stack Overflow or by Ernesto
Published on 2013-11-10T03:30:13Z Indexed on 2013/11/10 3:53 UTC
Read the original article Hit count: 291

Filed under:

At the risk of receiving negative votes, I will preface this by saying this is a midterm problem for a programming class. However, I have already submitted the code and passed the question. I changed the name of the function(s) so that someone can't immediately do a search and find the correct code, as that is not my purpose. I am actually trying to figure out what is actually MORE CORRECT from two pieces that I wrote.

The problem tells us that a certain fast food place sells bite-sized pieces of chicken in packs of 6, 9, and 20. It wants us to create a function that will tell if a given number of bite-sized piece of chicken can be obtained by buying different packs. For example, 15 can be bought, because 6 + 9 is 15, but 16 cannot be bought, because no combination of the packs will equal 15. The code I submitted and was "correct" on, was:

def isDivisible(n):
    """
    n is an int

    Returns True if some integer combination of 6, 9 and 20 equals n
    Otherwise returns False.
    """
    a, b, c = 20, 9, 6
    if n == 0:
        return True

    elif n < 0:
        return False

    elif isDivisible(n - a) or isDivisible(n - b) or isDivisible(n - c):
        return True

    else:
        return False

However, I got to thinking, if the initial number is 0, it will return True. Would an initial number of 0 be considered "buying that amount using 6, 9, and/or 20"? I cannot view the test cases the grader used, so I don't know if the grader checked 0 as a test case and decided that True was an acceptable answer or not. I also can't just enter the new code, because it is a midterm. I decided to create a second piece of code that would handle an initial case of 0, and assuming 0 is actually False:

def isDivisible(n):
    """
    n is an int

    Returns True if some integer combination of 6, 9 and 20 equals n
    Otherwise returns False.
    """
    a, b, c = 20, 9, 6
    if n == 0:
        return False
    else:
        def helperDivisible(n):
            if n == 0:
                return True

            elif n < 0:
                return False

            elif helperDivisible(n - a) or helperDivisible(n - b) or helperDivisible(n - c):
                return True

            else:
                return False
        return helperDivisible(n)

As you can see, my second function had to use a "helper" function in order to work. My overall question, though, is which function do you think would provide the correct answer, if the grader had tested for 0 as an initial input?

© Stack Overflow or respective owner

Related posts about python