my version of @dis.sociat.ing's dollcode algorithm in python

Feat: decode dollcode

- lossless decoding
- renamed functions for clarity

+34 -5
+34 -5
main.py
··· 5 5 parser = argparse.ArgumentParser(description="converts input into dollcode") 6 6 parser.add_argument("input", type=str, help="input to convert") 7 7 parser.add_argument("-c", action="store_true", help="copy output to clipboard") 8 + parser.add_argument("-d", action="store_true", help="decode dollcode") 8 9 args = parser.parse_args() 9 10 10 11 DOLLCODE_CHARS = ("▌", "▖", "▘") ··· 12 13 13 14 14 15 # encodes input string into integer by using ord() & base256 15 - def convert_to_int(input: str): 16 + def encode_base256_int(input: str): 16 17 result = 0 17 18 18 19 for char in input: ··· 21 22 return result 22 23 23 24 25 + # decodes input number back in char 26 + def decode_base256_int(num: int): 27 + output = "" 28 + 29 + while num > 0: 30 + char = chr(num % 256) 31 + output = char + output 32 + num = num // 256 33 + 34 + return output 35 + 36 + 24 37 # converts encoded base256 int -> bijective base-3 numeration 25 38 # then inserts corresponding number (3, 1, 2) into output list 26 - def convert_to_dollcode(num: int): 39 + def encode_dollcode(num: int): 27 40 output: list[str] = [] 28 41 window: int = num 29 42 ··· 40 53 return output 41 54 42 55 56 + # decodes input dollcode -> integer 57 + def decode_dollcode(input: str): 58 + result: int = 0 59 + 60 + for char in input: 61 + if char == DOLLCODE_CHARS[0]: 62 + result = (result + 1) * BASE_NUM 63 + else: 64 + result = result * BASE_NUM + DOLLCODE_CHARS.index(char) 65 + 66 + return result 67 + 68 + 43 69 # loops dollcode list, appends each output list entry to 44 70 # string, then prints or prints + copies if appropriate flag was passed 45 71 def print_dollcode(output: list[str], copy: bool): ··· 55 81 print(string) 56 82 57 83 58 - def main(input: str, copy: bool): 59 - print_dollcode(convert_to_dollcode(convert_to_int(input)), copy) 84 + def main(input: str, copy: bool, decode: bool): 85 + if decode: 86 + print(decode_base256_int(decode_dollcode(input))) 87 + else: 88 + print_dollcode(encode_dollcode(encode_base256_int(input)), copy) 60 89 61 90 62 91 if __name__ == "__main__": 63 - main(args.input, args.c) 92 + main(args.input, args.c, args.d)