Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading