0

I am trying to write a list rotation function in python. I came across with the the following code :

def move(p, U): q = [] for i in range(0,len(p)): q.append(p[(i-U)%len(p)]) return q 

This works perfect. But I am trying to figure out when len(p) = 5 and U = 1, why should be the result of -1 % 5 = 4 ?

0

2 Answers 2

0

It is 4. Python % operator always gives you a remainder with the same sign as the second operand. Thanks Mat for pointing it out.

-1 = (5) * (-1) + 4

Therefore, the remainder is 4.

http://docs.python.org/2/reference/expressions.html#binary-arithmetic-operations

Sign up to request clarification or add additional context in comments.

Comments

0

a % b will return a number with the sign of b.

However, your list rotation function would be better expressed as:

def move(l, n): n = n % len(l) return l[n:] + l[:n] 

1 Comment

Nice code. Also works when n is negative.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.