Reputation: 55
I am trying to do a custom base conversion in Python by converting from base 39 to base 10 and back. It works fine, except that I lose the last letter of my string:
#base 39(custom characters)
chars = 'esiarntolcdugpmhbyfvkwzxjq 0.,123456789'
nchars = len(chars)
#text that is converted (I am not bob btw)
text = 'hello everyone, bob here'
#convert to decimal
final = 0
for i, v in enumerate(text):
print(v)
final += nchars**i * chars.index(v)
text1 = ''
ind = 0
#convert back to custom base
while final >= 1:
print(final)
text1 += chars[final % nchars]
final = final // nchars
print(text1)
# prints hello everyone, bob her
What am I doing wrong?
Upvotes: 0
Views: 86
Reputation: 974
You don't systematically lose the last letter of text
, this actually only ever happens when it ends with the letter "e". So what's special about that particular letter? Well it starts (or, should I say, it is at index 0
of) your encoding dictionary, chars
. Therefore, what would the encoded value of 'e'
be? What final
value would that represent and what impact would that have on your decoding loop's condition?
I believe this is enough for you to find your bug. However, next time, try using a debugger and step through the code; you'll be able to see where the issue comes from.
Upvotes: 1