moonit
moonit

Reputation: 5

How to work only on ints in Python?

I have problem with my code. The task was to search for 3 integers that solves this equation 6*a+9*b+20*c = x, where x is an input. The problem is that my code only works for floats, and I unable to force it to give me an anwser only while a,b,c are integers.

Here's the code in Python:

def mc_nuggets(numWings):
    for Na in range(0, numWings + 1):
        for Nb in range(0, numWings - Na + 1):
            for Nc in range(0, numWings - Na - Nb + 1):
                num_a = (numWings -  9*Nb - 20*Nc)/6
                num_b = (numWings -  6*Na - 20*Nc)/9
                num_c = (numWings -  9*Nb - 6*Nc)/20
                if (6*num_a + 9*num_b + 20*num_c == numWings and type(num_a) is int == True and type(num_b) is int == True and type(num_c) is int == True):
                    return [num_a, num_b, num_c]
return [None, None, None]             

Do u have any ideas how to make it work?

Upvotes: 0

Views: 153

Answers (2)

moonit
moonit

Reputation: 5

my solution to the problem:

def mc_nuggets(numWings):
    for Na in range(0, numWings + 1):
        for Nb in range(0, numWings - Na + 1):
            for Nc in range(0, numWings - Na - Nb + 1):
                num_a = (numWings -  9*Nb - 20*Nc)
                num_b = (numWings -  6*Na - 20*Nc)
                num_c = (numWings -  9*Nb - 6*Na)
                if (num_a % 6 == 0 and num_b % 9 == 0 and num_c % 20 == 0):
                    if (num_a >= 0 and num_b >= 0 and num_c >= 0):
                        return [num_a/6, num_b/9, num_c/20]
     return [None, None, None]

Upvotes: 0

Holt
Holt

Reputation: 37626

Are you using python 2 or 3? On python 2, your code will truncate integer so it's incorrect.

On python 3, it is not because the value is 3.0 that the type is integer, it's float. To check if it's an integer value, use the is_integer method, see https://docs.python.org/2/library/stdtypes.html#float.is_integer.

Here is a method on how to make it without having to deal without float: You should iterate directly over a and b. Greater value for a is numwings / 6 (when b and c are 0). Then you could iterate b until (numwings - 6 * a) / 9. Once you get there, you know that 20 * c = numwings - 6 * a - 9 * b so you do not need your third loop, and you can easily check if there is an integer such as the previous equation is correct (check with modulo for example).

Upvotes: 1

Related Questions