I was doing a simple problem on codingbat and testing out my python. The problem was:
Given two int values, return their sum. Unless the two values are the same, then return double their sum.
sum_double(1, 2) → 3 sum_double(3, 2) → 5 sum_double(2, 2) → 8
My solution was:
def sum_double(a, b):
if a is b:
return 2 * (a + b)
else:
return a+b
and it worked just fine. However, when I checked the solution the answer they had was:
def sum_double(a, b): # Store the sum in a local variable sum = a + b # Double it if a and b are the same if a == b: sum = sum * 2 return sum
But this seems to Java-y to me. Am I right to believe that my code is more pythonic? Or was their answer a better way to write code in python?
return a==b?a*4:a+b;
... \$\endgroup\$ – Olivier Grégoire Sep 27 '16 at 10:28return 4 * a
be simpler thanreturn 2 * (a + b)
? \$\endgroup\$ – TRiG Sep 28 '16 at 15:02a << 2
but then again I wouldn't reason about it because since you branched already the interpreter may as well do the same thing for both cases. \$\endgroup\$ – noob Sep 29 '16 at 22:56