[英]How to fix the code for base62 encoding with Python3?
I am creating a python script for base62 encoding.我正在为 base62 编码创建一个 python 脚本。 However, for some reason, my code doesn't produce the correct answer.但是,由于某种原因,我的代码没有产生正确的答案。 Correct answer is LpuPe81bc2w, but i get LpuPe81bc0w.正确答案是 LpuPe81bc2w,但我得到了 LpuPe81bc0w。 If you can review my code and see if I can do any different.如果您可以查看我的代码,看看我是否可以做任何不同的事情。 Please let me know.请告诉我。 I can't use pybase62.我不能使用 pybase62。
I really want to know why my code doesn't work because I want to understand fundamental.我真的很想知道为什么我的代码不起作用,因为我想了解基础知识。 Preferably最好
NO PyBASE62 and I am a beginner.没有 PyBASE62,我是初学者。
base_62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
BASE = len(base_62)
def to_base_62(number):
rete=''
while number != 0:
rete = (base_62[number%BASE])+rete
number = int(number/BASE)
return rete
print (to_base_62(18327995462734721974))
You ran afoul of floating-point accuracy.您违反了浮点精度。 I inserted a simple tracking statement into your code:我在您的代码中插入了一个简单的跟踪语句:
def to_base_62(number):
rete=''
while number != 0:
rete = base_62[number%BASE]+rete
print(len(rete), number/BASE)
number = int(number/BASE)
return rete
Output: Output:
1 2.956128300441084e+17
2 4767948871679168.0
3 76902401156115.61
4 1240361308969.5967
5 20005827564.01613
6 322674638.12903225
7 5204429.645161291
8 83942.40322580645
9 1353.9032258064517
10 21.822580645161292
11 0.3387096774193548
LpuPe81bc0w
The floating-point division doesn't keep enough digits to differentiate the ones you need for a number this large.浮点除法没有保留足够的数字来区分这么大的数字所需的数字。 Instead, use integer division:相反,使用 integer 除法:
while number != 0:
rete = base_62[number%BASE]+rete
print(len(rete), number // BASE)
number = number // BASE
Output: Output:
1 295612830044108418
2 4767948871679168
3 76902401156115
4 1240361308969
5 20005827564
6 322674638
7 5204429
8 83942
9 1353
10 21
11 0
LpuPe81bc2w
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.