educative.io

Rotate linked list solution question - negative number modulo in Python

In the solution of “Rotate a Linked List” from python learning path. There’s a function I don’t quite understand:

def adjust_rotations_needed(n, length):

  # If n is positive then number of rotations performed is from right side
  # and if n is negative then number of rotations performed from left side
  # Let's optimize the number of rotations.
  # Handle case if 'n' is a negative number.

  n = n % length

  if n < 0:

    n = n + length

If I have n as -9, and length is 7, before hitting “if n<0”, n will be (-9) %7 = 5.
My question is, in what circumstance that the program will hit “if n< 0:” line?

Thanks.

n<0 is added as a handle case. One way in which n could be negative is in case of overflow. While Python throws an interrupt in case of an overflow, it cannot for the ones declared by pystack e.g. numpy library. In any case, adding handle cases is always a good practice as it makes your code more robust against edge cases.

@Evelyn_Dai

That’s a very good question. The program will never hit if n<0 in this scenario because if the operator on the right side of the mod (%) operator is positive, then the answer will never be less than 0. It’s just for an exception that if the length by any means passed as a negative number to this function only then, the program would execute if n< 0 d. e.g. (11 % -2) = -1.

I hope I have answered your query. If you have any further doubts, please feel free to contact us.

Thanks :blush: