recursion - Recursive addition/subtraction in python with negative integers -
recursion - Recursive addition/subtraction in python with negative integers -
i trying create programme adds , subtracts 2 arguments using recursion. far programme working positive integers lost how can create work negative integers. appreciate help.
here code far:
def add(x,y): """add takes x , y , adds them together""" if y == 0: homecoming x else: homecoming add1(add(x, sub1(y))) def sub(x,y): """sub takes x , y , subtracts them""" if y == 0: homecoming x else: homecoming sub1(sub(x, sub1(y))) def add1(x): homecoming x+1 def sub1(x): homecoming x-1
i'd go this
def add(x,y): if y > 0: homecoming add(x, y-1) + 1 elif y < 0: homecoming add(x, y+1) - 1 else: homecoming x
subtract same idea, flip signs
def sub(x,y): if y > 0: homecoming sub(x, y-1) - 1 elif y < 0: homecoming sub(x, y+1) + 1 else: homecoming x
testing
>>> add(3,5) 8 >>> add(3,0) 3 >>> add(3,-5) -2 >>> subtract(8,3) 5 >>> subtract(3,8) -5 >>> subtract(3,0) 3
python recursion negative-number
Comments
Post a Comment