itseva
itseva

Reputation: 593

Repeat array and stops at specific position w/ numpy

I have to write a cyclic functie cyclisch(N) that constructs a Numpy-row with length N with content[1.0 2.0 3.0 1.0 2.0 3.0 1.0 2.0 3.0 ...].

This is de code I'm having now.

import numpy as np
import math

def cyclisch(N):
    r = np.linspace(float(1.0), float(3.0), 3)
    return np.repeat(r, N//3) + r[0:N%3-1]

I tried multiple times to make the list 'r' float, but I get the error:

only length-1 arrays can be converted to Python scalars

Further, the repeating code is also wrong. With the repeat coding you get:

[ 1.  1.  2.  2.  3.  3.] 

Instead of [1.0 2.0 3.0 1.0 2.0 3.0 1.0 2.0 3.0 ...]. Does anyone know how to have this kind of repeating code?

This is the control mode:

p = cyclisch(10)
q = cyclisch(7)
assert np.all(p == np.array([ 1.,  2.,  3.,  1.,  2.,  3.,  1.,  2.,  3.,  1.])),'Fout resultaat van cyclisch(10)'
assert np.all(q == np.array([ 1.,  2.,  3.,  1.,  2.,  3.,  1.])),'Fout resultaat van cyclisch(7)'
print('Correct !')

Thank you for your help!

Upvotes: 2

Views: 118

Answers (2)

Jonas Adler
Jonas Adler

Reputation: 10759

You can use np.resize.

>>> np.resize([1., 2., 3.], 5)
array([ 1., 2., 3., 1., 2.])

This works since:

If the new array is larger than the original array, then the new array is filled with repeated copies of a.

Note that the np.ndarray.resize method has different behavior, padding with zeros (and also mutating the array instead of making a new one), so you need to use the function, not the method.

Upvotes: 3

Mr Tarsa
Mr Tarsa

Reputation: 6652

How about

>> N = 5
>> x = [1.0, 2.0, 3.0]
>> np.asarray(x * (N // 3) + x[:N % 3])
array([ 1.,  2.,  3.,  1.,  2.])                                                                                                                                                                                

Upvotes: 3

Related Questions