This simple Python code I wrote for a problem asked during an interview. The problem statement is:
Given a tuple (a, b), transform this into (c, d) by applying any of the two below operations multiple time in any order you like:
- (a, b) -> (a+b, b)
- (a, b) -> (a, a+b)
The program should take in a, b, c, and d. And tells us if it is possible to transform (a, b) to (c, d).
Edit: a, b, c and d can be negative integers.
This recursive solution seems correct but recursion depth increases very fast for even slight increase in input size. I feel I am missing some easy optimization here. I would be glad for any kind of inputs be it style, algorithm choice, speed etc.
def intro():
print "This program will check if transformation (a, b) -> (c, d) is possible by recursive application of any of the below rules:"
print "1. (a, b) => (a+b, b) \n2. (a, b) => (a, a+b)\n"
def user_input():
print "Enter space separated four integers a, b, c and d:\n"
a, b, c, d = map(int, raw_input().split(' '))
return a, b, c, d
# print 'a = ' + a + ' b = ' + b + ' c = ' + c + ' d = ' + d
def solve(a, b, c, d):
print '(a: {}, b: {}) (c: {}, d:{})'.format(a,b,c,d)
if a == c and b == d:
return True
elif a > c or b > d:
return False
elif a == c and b != d:
return solve(a, a+b, c, d)
elif a !=c and b == d:
return solve(a+b, b, c, d)
else:
return solve(a+b, b, c, d) or solve(a, a+b, c, d)
if __name__ == '__main__':
intro()
a, b, c, d = user_input()
if solve(a, b, c, d):
print "Transformation possible"
else:
print "Transformation not possible"
a
andb
must be nonnegative? \$\endgroup\$