This can be done with isinstance
, which is robust against things like
subclasses:
def _oddsum(n):
# efficient generator expression here
return sum(i for i in range(n + 1) if i % 2 == 1)
def oddsum(arr):
return [_oddsum(n) for n in arr]
def polymorph_oddsum(x):
if isinstance(x, list):
return oddsum(x)
return _oddsum(x)
if __name__ == "__main__":
# really all of these are more sensible ways to do this
print(oddsum([9]))
print(_oddsum(9))
print(oddsum([4, 5, 9]))
print(oddsum((4, 5, 9)))
print(oddsum({4, 5, 9}))
# but if you really wanted, you can use polymorph_oddsum for either case
print(polymorph_oddsum(9))
print(polymorph_oddsum([4, 5, 9]))
However as you might have seen from my comments, this probably isn't actually
what you want to do. You should just call the appropriate function depending on
what the type of your input is going to be, which you should really know before
runtime.
The isinstance
approach is less desirable because it breaks as soon as you
give it any other kind of iterable, though the normal oddsum
does not, as my
code shows.
Incidentally, while I have taken the liberty of putting your loop into a single
generator expression, you don't even need a loop here. The sum of odd numbers is
an easy progression to find a closed form for, and you can just use
def _oddsum2(n):
return ((n + 1) // 2) ** 2