0
votes

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)
1
Use the same code but append e twice. - Barmar
That's basically the second bit of the binary version of the number. (i >> 1) & 1 would give the desired value. - jasonharper
If you want to get fancy, you can use itertools.cycle to just repeat [0, 0, 1, 1] however many times you want. E.g. from itertools import islice, cycle; list(islice(cycle([0, 0, 1, 1]), 25)) will give a list with the first 25 items of this sequence - Alexander
Why are there two reopen votes here? It looks like a clear duplicate to me. - Karl Knechtel

1 Answers

8
votes

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.