2

I have a tasko to make a program in which i get m, n and k. I should create a list a with n*m element. List b is supposed to have n*m element. It is created from list a with cyclic shift k to the right for m elements of lists. I know it is poorly explained. Example is:

n=3
m=4
A=1 2 3 4 5 6 7 8 9 10 11 12
k=1
B=4 1 2 3 8 5 6 7 12 9 10 11

What i have at the moment is:

from random import randint
n = int(input())
m=int(input())

A = []
B=[0]
B=B*n*m
for i in range(n*m):
    A = A + [randint(1, 30)]

print('\nLista A:\n')
for i in range(n*m):
    print(A[i], end = ' ')

print()

k=int(input())

for i in range(-1, m*n, m):
    B[m-1-i]=A[i]
    print(B[m-1-i])

print('\nLista B:\n')
for i in range(n*m):
    print(B[i], end = ' ')

Thanks

karthikr
  • 97,368
  • 26
  • 197
  • 188
Srcheko
  • 21
  • 1

2 Answers2

1

Try this...

# Start with an empty list
B = []
# Take A in chunks of m
for i in range( int(len(A)/m) ):
    # Take an m-sized chunk of A
    chunk = A[m*i:m*(i+1)]
    # Shift it to the right by k (python style!)
    shift = chunk[-k:] + chunk[:-k]
    # Add it to B
    B += shift
print (B)
Jared N
  • 162
  • 7
0

Alternative:

m=4
n=3
k=1

A=list(range(1,1+m*n))
print (A)

t_1=[A[_:_+4] for _ in range(0,len(A), 4)]
print (t_1)

t_2=[]
for sublist in t_1:
    t_2.append(sublist[-k:]+sublist[:-k])
print (t_2)

B=[]
for sublist in t_2:
    B.extend(sublist)

print (B)

If you want greater speed then you could use a deque from the collections module to build t_2.

Here's the result.

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
[[4, 1, 2, 3], [8, 5, 6, 7], [12, 9, 10, 11]]
[4, 1, 2, 3, 8, 5, 6, 7, 12, 9, 10, 11]
Bill Bell
  • 21,021
  • 5
  • 43
  • 58
  • I get the point, but I can only do it with for, if or while since I just started learning python. – Srcheko Oct 17 '16 at 15:54