1. Miki Tebeka
  2. base62-py

Commits

Miki Tebeka  committed 6e9d5f2

main, cleanup and Python 3

  • Participants
  • Parent commits 4b805d6
  • Branches default

Comments (0)

Files changed (2)

File base62.py

View file
  • Ignore whitespace
 
 import string
 
-chars = string.digits + string.letters
+chars = string.digits + string.ascii_letters
 base = len(chars)
 
 
     return ''.join(reversed(digits))
 
 
-def decode1(string):
-    '''Decode a base62 string to a number.'''
-    strlen = len(string)
-    num = 0
-
-    idx = 0
-    for char in string:
-        power = (strlen - (idx + 1))
-        num += chars.index(char) * (base ** power)
-        idx += 1
-
-    return num
-
-
 def decode(string):
     '''Decode a base62 string to a number.'''
     loc = chars.index
         num += loc(ch) * (base ** (size - i))
 
     return num
+
+
+def main(argv=None):
+    import sys
+    from argparse import ArgumentParser
+
+    argv = argv or sys.argv
+
+    parser = ArgumentParser(description='encode/decode in base62')
+    parser.add_argument('n', help='number to encode/decode')
+    parser.add_argument('--encode', '-e', help='encode (default)',
+                        action='store_true', default=False)
+    parser.add_argument('--decode', '-d', help='decode', action='store_true',
+                        default=False)
+    args = parser.parse_args(argv[1:])
+
+    if args.encode and args.decode:
+        raise SystemExit('error: cannot have both -e and -d')
+
+    if args.decode:
+        print(decode(args.n))
+        raise SystemExit
+
+    try:
+        n = int(args.n)
+    except ValueError:
+        raise SystemExit('error: bad number')
+
+    print(encode(n))
+
+if __name__ == '__main__':
+    main()

File test_base62.py

View file
  • Ignore whitespace
 
 def check(n, b62):
     assert base62.encode(n) == b62, 'bad encode'
-    assert base62.decode1(b62) == n, 'bad decode'
+    assert base62.decode(b62) == n, 'bad decode'
 
 
 test_cases = [