2

I'm trying to create a list (b) that is list (a) rotating a's members k times to the left. I came up with this on Python 3:

n = 5
k = 4
a = [1,2,3,4,5]
b = []

for i in a:
    if (i + k) <= (n - 1):
            b.append(a[i+k])
        elif (i+k-n) < (n-1):
                b.append(a[i+k-n])      
print(b) 

But for some reason, it doesn't work since when I tell print(b) it returns a list that is exactly like list a

What am I missing here?

Salvatore
  • 41
  • 5
  • 1
    Note that `i ` cycles through the _values_ in `a` , which should be pretty irrelevant to your algorithm, and you are doing arithmetic with them as if they're indices. – RemcoGerlich Jun 21 '17 at 18:58
  • 1
    Possible duplicate of [Python list rotation](https://stackoverflow.com/questions/9457832/python-list-rotation) – JohanL Jun 21 '17 at 18:59
  • @RemcoGerlich you're totally right! Changing the for loop for a while loop did the trick – Salvatore Jun 21 '17 at 20:04

2 Answers2

5

A simple solution:

k = k % len(a) #we don't care about shifting x*len(a) times since it does not have any effect

b = a[k:] + a[:k]
Yoav Glazner
  • 7,936
  • 1
  • 19
  • 36
  • hi @YoavGlazner, could you unravel your code for us a little bit? I'm picking up programming after a 15 years break hehe, and I'm not too familiar with Python's syntax since I really just started learning it – Salvatore Jun 21 '17 at 20:11
  • @Salvatore - I guess that you are not aware of **python's** *slice-notation* - take a look at this answer https://stackoverflow.com/questions/509211/explain-slice-notation – Yoav Glazner Jun 22 '17 at 04:02
1

Thanks to @RemcoGerlich for helping me see my mistake! Here's how I quickly fixed my code:

n = 5
k = 4
a = [1,2,3,4,5]
b = []
i = 0
while (i < n):
    if (i + k) <= (n - 1):
            b.append(a[i+k])
    elif (i+k-n) < (n-1):
            b.append(a[i+k-n])
    i = i+1
print(b)
Salvatore
  • 41
  • 5