tags:

views:

41

answers:

1

I want to implement a similar function, and want to accept an array or number that I pass to numpy.ones.

Specifically, I want to do this:

def halfs(shape):
    shape = numpy.concatenate([2], shape)
    return 0.5 * numpy.ones(shape)

Example input-output pairs:

# default
In [5]: beta_jeffreys()
Out[5]: array([-0.5, -0.5])

# scalar
In [5]: beta_jeffreys(3)
Out[3]: 
array([[-0.5, -0.5, -0.5],
       [-0.5, -0.5, -0.5]])

# vector (1)
In [3]: beta_jeffreys((3,))
Out[3]: 
array([[-0.5, -0.5, -0.5],
       [-0.5, -0.5, -0.5]])

# vector (2)
In [7]: beta_jeffreys((2,3))
Out[7]: 
array([[[-0.5, -0.5, -0.5],
        [-0.5, -0.5, -0.5]],

       [[-0.5, -0.5, -0.5],
        [-0.5, -0.5, -0.5]]])
+1  A: 
def halfs(shape=()):
    if isinstance(shape, tuple):
        return 0.5 * numpy.ones((2,) + shape)
    else:
        return 0.5 * numpy.ones((2, shape))



a = numpy.arange(5)
# array([0, 1, 2, 3, 4])


halfs(a.shape)
#array([[ 0.5,  0.5,  0.5,  0.5,  0.5],
#       [ 0.5,  0.5,  0.5,  0.5,  0.5]])

halfs(3)
#array([[ 0.5,  0.5,  0.5],
#       [ 0.5,  0.5,  0.5]])
eumiro
I have now edited it and made shape optional, as you stated in your comment. So you can call it with `halfs()` and it will return a 1-dimensional array of two 0,5 elements.
eumiro
This looks good when shape is an array, but this doesn't work with ints. How does numpy accept arrays or scalars?
Neil G
@Neil, you have to write an example in your original question with example input and output.
eumiro
thanks for making the default parameter work.
Neil G
@Neil, I think I understand what you mean and I have edited it now along with examples. However, this is not very clean way to go and it makes your code more difficult to debug.
eumiro
@eumiro, thank you very much. this is exactly what I was looking for. Presumably, numpy.ones does a similar test for tuple-ness internally?
Neil G