Dalla Rosa

Posts tagged math

0 notes &

Code of the day: Circular shift for integers (python)

"x" is the number you want to rotate. "n" is the number of rotations you want to apply.
While writing this I actually felt how slow python’s math lib is. I’ve wrote this a while ago, but iirc a version I wrote using string operations was actually faster than this.
I managed to get to a pretty fast version later on but it involves caching all functions in local variables, replacing range with xrange and a bunch of other little improvements. I’ll keep this version because it pretty readable and it’s pretty self-explanatory on how to shift rotate numbers.
It was very fun trying to get every little millisecond I could from the code and I might just write a post on the differences of performance for each implementation I did.

def rotate(x,n):
  result = x
  mag_x = len(str(x))
  for i in range(0,n):
    mag_res = len(str(result))
    first = 0 if mag_x > mag_res else int(result/pow(10,mag_res))
    tmp = result - first*pow(10,mag_res)
    result = tmp*10 + first
  return result

Filed under code python math tech integer circular shift