-1

i have been working on this for 3 hours now but i have no clue how to do it

can anyone help me with this?

values = [1, 2, 3, 4, 5]

temp = values[0]

for index in range (len(values) -1):
    values[index] = values [index]

values[len(values)-1] = temp
print values

i want the printed values to be in order as [2,3,4,5,1] by simply changing those in the brackets

4

4 Answers 4

3

deque is more efficient way to do

In [1]: import collections

In [3]: dq = collections.deque([1,2,3,4,5])

In [4]: dq.rotate(-1)

In [5]: dq
Out[5]: deque([2, 3, 4, 5, 1])
1
  • 1
    Nevertheless, it is more efficient and moreover it will work well with any iterables
    – Abhijit
    May 29, 2015 at 10:51
1

What you are trying to achieve is not available in the python libraries but you can leverage slicing to rotate list

Implementation

def rotate(seq, n = 1, direc = 'l'):
    if direc.lower() == 'l':
        seq = seq[n:] + seq[0:n]
    else:
        seq = seq[-n:] + seq[:-n]
    return seq

Demonstration

>>> rotate(values)
[2, 3, 4, 5, 1]
>>> rotate(values,2,'l')
[3, 4, 5, 1, 2]
>>> rotate(values,2,'r')
[4, 5, 1, 2, 3]
0

Simple but powerful slice syntax:

values = [1, 2, 3, 4, 5]
shifted = values[1:]+values[:1]
assert shifted == [2, 3, 4, 5, 1]
0

How about time one-liner, in the spirit of sleepsort:

while values != [2, 3, 4, 5, 1]: random.shuffle(values)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.