Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What will be the best approach for a digit like pattern in python?

Tags:

python

i was trying a pattern in Python if n == 6

1 2 3 4 5
2 3 4 5 1
3 4 5 1 2
4 5 1 2 3
5 1 2 3 4

after trying to think a lot i did it like this --->

n = 6

for i in range(1,n):
    x = 1
    countj = 0
    for j in range(i,n):
        countj +=1
        print(j,end=" ")
        if j == n-1 and countj < n-1 :
            while countj < n-1:
                print(x , end =" ")
                countj +=1
                x +=1
        
    print()

but i don't think it is the best approach, I was trying to search some better approach , but not able to get the proper one, So that I came here,, is there any possible better approach for the problem?

like image 764
Pallab Tewary Avatar asked Dec 09 '22 23:12

Pallab Tewary


1 Answers

I would do like this, using a rotating deque instance:

>>> from collections import deque
>>> n = 6
>>> d = deque(range(1, n))
>>> for _ in range(1, n):
...     print(*d)
...     d.rotate(-1)
... 
1 2 3 4 5
2 3 4 5 1
3 4 5 1 2
4 5 1 2 3
5 1 2 3 4

There is a similar/shorter code possible just using range slicing, but maybe it's a bit harder to understand how it works:

>>> ns = range(1, 6)
>>> for i in ns:
...     print(*ns[i-1:], *ns[:i-1])
... 
1 2 3 4 5
2 3 4 5 1
3 4 5 1 2
4 5 1 2 3
5 1 2 3 4

You could also create a mathematical function of the coordinates, which might look something like this:

>>> for row in range(5):
...     for col in range(5):
...         print((row + col) % 5 + 1, end=" ")
...     print()
... 
1 2 3 4 5 
2 3 4 5 1 
3 4 5 1 2 
4 5 1 2 3 
5 1 2 3 4 

A too-clever way using list comprehension:

>>> r = range(5)
>>> [[1 + r[i - j - 1] for i in r] for j in reversed(r)]
[[1, 2, 3, 4, 5],
 [2, 3, 4, 5, 1],
 [3, 4, 5, 1, 2],
 [4, 5, 1, 2, 3],
 [5, 1, 2, 3, 4]]

more-itertools has this function:

>>> from more_itertools import circular_shifts
>>> circular_shifts(range(1, 6))
[(1, 2, 3, 4, 5),
 (2, 3, 4, 5, 1),
 (3, 4, 5, 1, 2),
 (4, 5, 1, 2, 3),
 (5, 1, 2, 3, 4)]
like image 163
wim Avatar answered Mar 30 '23 00:03

wim