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 ?

joydip134
  • 207
  • 1
  • 2
  • 9

2 Answers2

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

Community
  • 1
  • 1
Buddhima Gamlath
  • 2,318
  • 1
  • 16
  • 26
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]
Max Noel
  • 8,810
  • 1
  • 27
  • 35