HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMajor

Sum two integers, unless they are the same, in which case return double their sum

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
casesametheunlessarereturntwodoublesumwhich

Problem

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?

Solution

The existing answers mostly have just said is is wrong here. Which it undoubtedly is.
The reason it's bad to use here is if you pass 257 and above, or -6 and below, you may get incorrect output.
The best way to show how it's bad is to ask you what the output of the following are:

sum_double(2, 2)
sum_double(1 + 1, 2)
sum_double(257, 257)
sum_double(256 + 1, 257)


Simple! Surely it's 8, 8, 1028 and 1028, right?
No, it's actually, 8, 8, 1028 and 514.

This is known and expected behaviour:


The current implementation keeps an array of integer objects for all integers between -5 and 256,
when you create an int in that range you actually just get back a reference to the existing object.

Other than that both are fine, and I wouldn't really fret over which is 'better', this is as both are clear and understandable.
Which is all your code needs to be.

A function that would be un-pythonic, as it's not clear could be:

def sum_double(a, b):
    return (a + b) * ((a == b) + 1)

Code Snippets

sum_double(2, 2)
sum_double(1 + 1, 2)
sum_double(257, 257)
sum_double(256 + 1, 257)
def sum_double(a, b):
    return (a + b) * ((a == b) + 1)

Context

StackExchange Code Review Q#142559, answer score: 21

Revisions (0)

No revisions yet.