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

Question:

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)
Asked By: gameveloster

||

Answers:

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.

Answered By: Silvio Mayolo
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.