Generating the sequence 0, 0, 1, 1, 0, 0, 1, 1, … in Python

Using % 2 gives me the alternating sequence [0, 1, 0, 1, ...]

seq = []
for i in range(10):
    e = i % 2
    seq.append(e)

Is there a way to generate the sequence [0, 0, 1, 1, 0, 0, 1, 1,...] by generating the element from inside the loop?

seq = []
for i in range(10):
    e = the_solution(i)
    seq.append(e)

>Solution :

It sounds like you want to slow your existing sequence down, effectively doubling the length of each element. That is, indices 0 and 1 of your new sequence should correspond to index 0 of your old; 2 and 3 of your new sequence should correspond to index 1 of the old; and so on. We can use integer division to get this behavior.

e = (i // 2) % 2

// is like / but it rounds down to the next integer, so 2 // 2 and 3 // 2 are both 1.

Leave a Reply