How do I name a function that takes an object `A` and a set `{A, B}` as arguments, then returns `B`? [closed]

StackOverflow https://stackoverflow.com/questions/23179672

Question

What is a good name for the following function (as implemented in Python)?

def a_function(element, a_set):
    if a_set[0] == element:
        return a_set[1]
    if a_set[1] == element:
        return a_set[0]

assert 'A' == a_function('B', ['A', 'B'])
Était-ce utile?

La solution

I would use a different function name, different argument names and a docstring to make it clear what's going on, something like:

def get_other(current, both):
    """Return the element from 'both' that is not 'current'."""
    ...

Note that both implies a pair without anything long-winded, and doesn't specify the type required.

You can use your own implementation or Joel's; as long as the function does what it says, it doesn't really matter how it's implemented (barring performance concerns, edge cases, etc.).

However, to work with non-indexable containers (like the set, or the keys of a dict) without having to explicitly test what both is, I would probably go for:

def get_other(current, both):
    """Return the element from 'both' that is not 'current'."""
    for item in both:
        if item != current:
            return item

Indeed, if len(both) > 2, this will just return the first item in it that isn't equal to current - you can add checks for this if this is not the desired behaviour.

Autres conseils

As an alternative to what jonrsharpe proposes (which I like, don't get me wrong), here is a one-line version that uses sets as mentioned in the question title:

>>> def get_other(element, pair):
...   """Get the other element from a pair"""
...   return (set(pair) - set([element])).pop()
... 

This computes the set difference of element and pair then pops a random member from the resulting set (which should ideally be of size 1).

Here's a few examples of it working over different iterable data types:

>>> get_other('B', {'A', 'B'})
'A'
>>> get_other('B', ['A', 'B'])
'A'
>>> get_other('A', ['A', 'B'])
'B'
>>> get_other('B', {'A': 1, 'B': 2})
'A'
>>> get_other('B', 'AB')
'A'
>>> get_other(5, {1, 5})
1

If len(pair) > 2 or element not in pair, the element you get back is undefined, but will always be an element from pair:

>>> get_other('B', 'ABC')
'C'
>>> get_other('B', 'ABCDEF')
'E'

Finally, if pair is empty or pair == {element}, it will raise a KeyError:

>>> get_other('B', 'B')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in get_other
KeyError: 'pop from an empty set'
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top