Python | Print list elements in circular range
Given a list of elements, the task is to print element in group of k till n-iteration in circular range. Examples:
Input: list = [1, 2, 3, 4, 5, 6, 7], k = 3, n =10
Output:
[1, 2, 3]
[4, 5, 6]
[7, 1, 2]
[3, 4, 5]
[6, 7, 1]
[2, 3, 4]
[5, 6, 7]
[1, 2, 3]
[4, 5, 6]
[7, 1, 2]
Input: list = [10, 20, 30, 40, 50, 60, 70], k = 4, n = 5
Output:
[10, 20, 30, 40]
[50, 60, 70, 10]
[20, 30, 40, 50]
[60, 70, 10, 20]
[30, 40, 50, 60]
We can use itertools with zip to do this task. Example #1:
Python3
from itertools import cycle
List = [ 90 , 99 , 192 , 0 , 43 , 55 ]
n = 9
k = 5
for index, * ans in zip ( range (n), * [cycle( List )] * k):
print (ans)
|
Output:
[90, 99, 192, 0, 43]
[55, 90, 99, 192, 0]
[43, 55, 90, 99, 192]
[0, 43, 55, 90, 99]
[192, 0, 43, 55, 90]
[99, 192, 0, 43, 55]
[90, 99, 192, 0, 43]
[55, 90, 99, 192, 0]
[43, 55, 90, 99, 192]
Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(n), where n is the length of the output list.
Example #2:
Python3
from itertools import cycle
List = [ 'Geeks' , 'for' , 'geeks' , 'is' , 'portal' ]
n = 4
k = 6
for index, * ans in zip ( range (n), * [cycle( List )] * k):
print (ans)
|
Output:
['Geeks', 'for', 'geeks', 'is', 'portal', 'Geeks']
['for', 'geeks', 'is', 'portal', 'Geeks', 'for']
['geeks', 'is', 'portal', 'Geeks', 'for', 'geeks']
['is', 'portal', 'Geeks', 'for', 'geeks', 'is']
Example #3: Using slicing
This approach works by calculating the start and end indices for each iteration using the modulus operator to ensure that the indices wrap around to the beginning of the list when they exceed the length of the list.
Python3
def print_circular_range(lst, k, n):
for i in range (n):
start = i * k % len (lst)
end = (start + k) % len (lst)
if end > start:
print (lst[start:end])
else :
print (lst[start:] + lst[:end])
lst = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 ]
print_circular_range(lst, 3 , 10 )
|
Output
[1, 2, 3]
[4, 5, 6]
[7, 1, 2]
[3, 4, 5]
[6, 7, 1]
[2, 3, 4]
[5, 6, 7]
[1, 2, 3]
[4, 5, 6]
[7, 1, 2]
Time complexity: O(n)
Auxiliary Space: O(1)
Last Updated :
20 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...