0

I'm trying to write a function that accepts either a float OR an array of floats, and handles both of them using the same lines of code. For example, I want to return the float itself if it's a float, and the sum of the array of floats if it's an array. Something like this

def func(a):
  return np.sum(a)

and have both func(1.2) return 1.2, and func(np.array([1.2,1.3,1.4]) return 3.9.

4 Answers 4

2

The usual way to make sure the input is a NumPy array is to use np.asarray():

import numpy as np

def func(a):
  a = np.asarray(a)
  return np.sum(a)

func(1.2)
# 1.2
func([1.2, 3.4])
# 4.6
func(np.array([1.2, 3.4]))
# 4.6

or, if you want to get len() of your array, make sure it is at least 1-dimensional, use np.atleast_1d():

def func(a):
  a = np.atleast_1d(a)
  return a.shape[0]

func(1.2)
# 1
func([1.2, 3.4])
# 2
func(np.array([1.2, 3.4]))
# 2
Sign up to request clarification or add additional context in comments.

Comments

1

This already works, where's the problem?

import numpy as np
def func(a):
  return np.sum(a)
print(func(np.array([1.2,2.3,3.2])))
print(func(1.2))

Output:

6.7
1.2

2 Comments

You're right. Actually the problem I was facing before was that I was trying to return the length rather than the sum, and it gave me an error that floats don't have a 'len' property. Sorry, I should've included that. Do you know how to handle that?
Can you please update your question to reflect that? Including the error message will help as well.
1

You can use argument flattening:

def func(*args):
    # code to handle args
    return sum(args)

Now the following have the same behaviour:

>>> func(3)
3
>>> func(3, 4, 5)
12
>>> func(*[3, 4, 5])
12

Comments

0

You can check if the input is a float, and then put it in a list before processing the sum:

def func(a):
    if isinstance(a, float):
        a = [a]
    return np.sum(a)

2 Comments

This is too restrictive. What if the user passes in an int, or anything else that supports addition?
In the general case we might want to restrict the types, it depends on what the function does. But yes, if we want to do so the code should check the types properly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.