Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a cyclic sequence of numbers without using looping?

I want to generate a cyclic sequence of numbers like: [A B C A B C] with arbitrary length N I tried:

import numpy as np
def cyclic(N):
    x = np.array([1.0,2.0,3.0]) # The main sequence
    y = np.tile(x,N//3) # Repeats the sequence N//3 times 
    return y

but the problem with my code is if i enter any integer which ain't dividable by three then the results would have smaller length (N) than I excpected. I know this is very newbish question but i really got stuck

like image 771
Sam Farjamirad Avatar asked Jan 04 '23 05:01

Sam Farjamirad


1 Answers

You can just use numpy.resize

x = np.array([1.0, 2.0, 3.0])

y = np.resize(x, 13)

y
Out[332]: array([ 1.,  2.,  3.,  1.,  2.,  3.,  1.,  2.,  3.,  1.,  2.,  3.,  1.])

WARNING: This is answer does not extend to 2D, as resize flattens the array before repeating it.

like image 169
Daniel F Avatar answered Jan 13 '23 13:01

Daniel F