Simple way to calculate padding based on modulo/remainder

女生的网名这么多〃 提交于 2019-12-23 19:42:07

问题


If I have a string of length L=77 that I want to pad to a length that is a multiple of N=10. I am interested in computing just the amount of padding required. This can be easily done with N - (L % N), except for cases where L % N is zero.

I have been using the following for now:

pad = (N - (L % N)) % N

This does not seem particularly legible, so sometimes I use

pad = N - (L % N)
if pad == N:
    pad = 0

It seems overkill to use three lines of code for something so simple.

Alternatively, I can find the k for which k * N >= L, but using math.ceil seems like overkill as well.

Is there a better alternative that I am missing? Perhaps a simple function somewhere?


回答1:


The modulus of negative L will do it.

pad = -L % N



回答2:


Isn't this one enough?

pad = (N - L) % N



回答3:


With math.ceil:

from math import ceil

def pad(l, n):
    return n*ceil(l/n) - l

assert pad(59, 10) == 1
assert pad(60, 10) == 0
assert pad(61, 10) == 9



回答4:


I mean couldn't you simply do

pad = N-L if N-L > 0 else 0



回答5:


Use the tenary conditional operator:

0 if (L % N) == 0 else N - (L % N) 


来源:https://stackoverflow.com/questions/49903319/simple-way-to-calculate-padding-based-on-modulo-remainder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!