52 lines
1.0 KiB
Python
52 lines
1.0 KiB
Python
from typing import Iterable
|
|
|
|
|
|
def digit_to_char(digit):
|
|
if digit < 10:
|
|
return str(digit)
|
|
return chr(ord('A') + digit - 10)
|
|
|
|
|
|
def str_base(number, base):
|
|
if number < 0:
|
|
return '-' + str_base(-number, base)
|
|
(d, m) = divmod(number, base)
|
|
if d > 0:
|
|
return str_base(d, base) + digit_to_char(m)
|
|
return digit_to_char(m)
|
|
|
|
|
|
def unicode_ascii_repr(ascii: int) -> str:
|
|
if 0 <= ascii < 32:
|
|
return chr(ascii + 0x2400)
|
|
elif 32 <= ascii < 127:
|
|
return chr(ascii)
|
|
elif ascii == 127:
|
|
return chr(33 + 0x2400)
|
|
# Rip 🂢
|
|
return "‧"
|
|
|
|
|
|
def int_distance(lhs: int, rhs: int) -> int:
|
|
if lhs == rhs:
|
|
return 0
|
|
|
|
distance = 0
|
|
|
|
while lhs > 0 and rhs > 0:
|
|
if lhs & 1 != rhs & 1:
|
|
distance += 1
|
|
lhs >>= 1
|
|
rhs >>= 1
|
|
|
|
return distance
|
|
|
|
|
|
def int_distance_sort_key(item: int, all_items: Iterable[int]) -> int:
|
|
return sum(
|
|
map(
|
|
lambda i: int_distance(i, item),
|
|
all_items
|
|
)
|
|
)
|