Reputation:
How can we get list output in range ?
suppose n=4 and k =3
so how can we get list [1,2,3,1] where length of array will be n and k is range (1....k)
ex -2
if n=5 and k=3
list will be [1,2,3,1,2]
Upvotes: 1
Views: 111
Reputation: 16747
Short solution:
[i % k + 1 for i in range(n)]
and another a bit longer solution:
[i for j in range((n + k - 1) // k) for i in range(1, k + 1)][:n]
and similar to above but expressed differently
(list(range(1, k + 1)) * ((n + k - 1) // k))[:n]
Upvotes: 1
Reputation: 2379
You can get it done with itertools
:
import itertools
k,n = 3, 5
result = []
# defining iterator
iterators = itertools.cycle(list(range(1,k+1)))
# for in loop
for i in range(n):
x.append(next(iterators))
print(x)
Upvotes: 0
Reputation: 5026
A solution with itertools.cycle
def rangelist(n, k):
return [i for i,_ in zip(cycle(range(1,k+1)), range(n))]
rangelist(n=5,k=3)
>>> [1, 2, 3, 1, 2]
Upvotes: 0
Reputation: 517
Try this:
n = 5
k = 3
current_number = 1
ls = []
for count in range(n):
ls.append(current_number)
current_number = ((current_number) % k) + 1
Upvotes: 0
Reputation: 24282
You can use itertools.cycle to cycle on the values of a range from 1 to k, then use itertools.islice to get n values from it:
from itertools import cycle, islice
k = 3
n = 7
k_cycle = cycle(range(1, k+1))
out = list(islice(k_cycle, n))
print(out)
# [1, 2, 3, 1, 2, 3, 1]
Upvotes: 1
Reputation:
Try this
n,k = map(int,input().strip().split())
x=[]
for i in range(n):
x.append(1+i%k)
print(x)
Upvotes: 0