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

repeat a sequence of numbers N times and incrementally increase the values in the sequence Python

I have a number sequence as below

sequence = (0,0,1,1,1,1)

I want the number sequence to repeat a specified number of times but incrementally increase the values within the sequence

so if n= 3 then the sequence would go 1,1,2,2,2,2,3,3,4,4,4,4,5,5,6,6,6,6

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

I can make a sequence like below but the range function is not quite right in this instance

n = 3
CompleteSequence =  [j + k for j in range(0, n, 2) for k in sequence]
CompleteSequence 
[0, 0, 1, 1, 1, 1, 2, 2, 3, 3, 3, 3]

I have tried itertools

import itertools
sequence = (0,0,1,1,1,1)
n=3
list1 = list(itertools.repeat(sequence,n))
list1

[(0, 0, 1, 1, 1, 1), (0, 0, 1, 1, 1, 1), (0, 0, 1, 1, 1, 1)]

How can I go I achieve the pattern I need? a combination of range and itertools?

>Solution :

You can achieve this pattern with range() and an increment variable:

sequence = (0,0,1,1,1,1)
n = 3

CompleteSequence = []
increment = 1
for i in range(1, n+1):
    for j in sequence:
        CompleteSequence.append(j + increment)
    increment += 2

CompleteSequence now holds:

[1, 1, 2, 2, 2, 2, 3, 3, 4, 4, 4, 4, 5, 5, 6, 6, 6, 6]
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