Reputation: 846
Looking for a pythonic way to repeat sequences of fixed length while incrementing the sequence digits until max length is reached.
As of now, the code uses while loop and four variables one being the list itself to complete the logic as below,
l = []
i, repeat, max_len = 0, 3, 20
while True:
if len(l) + repeat <= max_len:
l.extend([i] * repeat)
else:
repeat = max_len - len(l)
l.extend([i] * repeat)
break
i += 1
The above code produces
l = [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6]
Thus, repeating a fixed length sequence of 3 units until the maximum length of 20 is reached (omit any last digits of sequence outside max_len permitted)
Is there a pythonic way of doing the same?
Upvotes: 1
Views: 406
Reputation: 29397
With list comprehensions
>>> i, repeat, max_len = 0, 3, 20
>>> q = max_len//repeat
>>> [x for x in range(i, i+q) for y in range(repeat)]+[i+q for y in range(max_len%repeat)]
[0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6]
With a different starting value:
>>> i = 5
>>> [x for x in range(i, i+q) for y in range(repeat)]+[i+q for y in range(max_len%repeat)]
[5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10, 11, 11]
Upvotes: 0
Reputation: 1
Well this will make exactly your list using list comprehension.
l = [i//(repeat) for i in range(max_len)]
# [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6]
But I think there is a bug in the original function because there should be three 5
s at the end.
l = [i//(repeat) for i in range(max_len//repeat * repeat)]
# [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5]
Upvotes: 0