vendredi 30 avril 2021

Testing two conditions in python. One condition is always true even when it is not supposed to be

I am having difficulties getting this code to work. I am attempting to do the following.

  1. When x is raised to a power of y, it needs to be true except with number 1.
  2. Return true when x is divisible by y.

Problems. I wrote this code but the problem is that when I input x=3 and y=3 I get and answer that x is the power of y which isn't true. Regardless of the number, if x == y it always says that x is power of y.

Question.

How would you make the corrections for this code?

def is_divisible(x, y):
    if x % y == 0:
        print("x is divisible by y")
        return True
    else:
        print("x is not divisible by y")
        print("x is not the power of y")
        return False


def is_power(x, y):
    if x == 1 or y == 1:  # code to test the base of 1
        return x == 1

    elif x % y == 0:
        print("x is the power of y")
        print("x is divisible by y")
    elif is_divisible(x, y) and is_power(x / y, y): # recursion of is_divisible. This will be true only if x/y
    # then x is the power of y.
        return 0.0
    else:
        return False
    


print(is_power(2, 2))

outputs

x is the power of y
x is divisible by y
None


print(is_power(27, 3))
x is the power of y
x is divisible by y
None
   

Aucun commentaire:

Enregistrer un commentaire