1 回答

TA貢獻(xiàn)1869條經(jīng)驗(yàn) 獲得超4個(gè)贊
RUC 的驗(yàn)證數(shù)字是使用與稱為 的方法非常相似(但不等于)的公式計(jì)算的Modulo 11;這至少是我在閱讀以下技術(shù)網(wǎng)站時(shí)獲得的信息(內(nèi)容為西班牙語(yǔ)):
https://www.yoelprogramador.com/funncion-para-calcular-el-digito-verificador-del-ruc/
http://groovypy.wikidot.com/blog:02
https://es.wikipedia.org/wiki/C%C3%B3digo_de_control#M.C3.B3dulo_11
我分析了上述頁(yè)面中提供的解決方案,并針對(duì) RUC 列表及其已知驗(yàn)證數(shù)字運(yùn)行了自己的測(cè)試,這使我得出了一個(gè)返回預(yù)期輸出的最終公式,但與上述鏈接中的解決方案不同。
我得到的計(jì)算 RUC 驗(yàn)證數(shù)字的最終公式如本例 ( 80009735-1) 所示:
將 RUC 的每個(gè)數(shù)字(不考慮驗(yàn)證數(shù)字)乘以基于該數(shù)字在 RUC 內(nèi)的位置(從 RUC 右側(cè)開始)的因子,并將這些乘法的所有結(jié)果相加:
RUC: 8 0 0 0 9 7 3 5
Position: 7 6 5 4 3 2 1 0
Multiplications: 8x(7+2) 0x(6+2) 0x(5+2) 0x(4+2) 9x(3+2) 7x(2+2) 3x(1+2) 5x(0+2)
Results: 72 0 0 0 45 28 9 10
Sum of results: 164
將總和除以11并使用除法的余數(shù)來(lái)確定驗(yàn)證數(shù)字:
如果余數(shù)大于1,則校驗(yàn)位為11 - remainder
若余數(shù)為0或1,則校驗(yàn)位為0
在輸出示例中:
Sum of results: 164
Division: 164 / 11 ==> quotient 14, remainder 10
Verification digit: 11 - 10 ==> 1
這是我Python的公式版本:
def calculate_dv_of_ruc(input_str):
# assure that we have a string
if not isinstance(input_str, str):
input_str = str(input_str)
# try to convert to 'int' to validate that it contains only digits.
# I suspect that this is faster than checking each char independently
int(input_str)
the_sum = 0
for i, c in enumerate(reversed(input_str)):
the_sum += (i + 2) * int(c)
base = 11
_, rem = divmod(the_sum, base)
if rem > 1:
dv = base - rem
else:
dv = 0
return dv
測(cè)試這個(gè)函數(shù)會(huì)返回預(yù)期的結(jié)果,當(dāng)輸入的字符不是數(shù)字時(shí)會(huì)引發(fā)錯(cuò)誤:
>>> calculate_dv_of_ruc(80009735)
1
>>> calculate_dv_of_ruc('80009735')
1
>>> calculate_dv_of_ruc('80009735A')
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "<input>", line 8, in calculate_dv_of_ruc
ValueError: invalid literal for int() with base 10: '80009735A'
添加回答
舉報(bào)