Skip to content

Instantly share code, notes, and snippets.

@VivaRado
Last active April 26, 2023 14:00
Show Gist options
  • Save VivaRado/c228baf3047d44ee73f2e2b80df0912f to your computer and use it in GitHub Desktop.
Save VivaRado/c228baf3047d44ee73f2e2b80df0912f to your computer and use it in GitHub Desktop.
Round to Closest Half Integer and Remove Trailing .0
import re
def close_half_int(number):
"""Round a number to the closest half integer.
>>> close_half_int(1.3)
1.5
>>> close_half_int(2.6)
2.5
>>> close_half_int(3.0)
3.0
>>> close_half_int(4.1)
4.0"""
return round(number * 2) / 2
COMMANDS = set('MmZzLlHhVvCcSsQqTtAa')
COMMAND_RE = re.compile("([MmZzLlHhVvCcSsQqTtAa])")
FLOAT_RE = re.compile("[-+]?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?")
def tokenize_path(pathdef):
flt = []
end = False
for x in COMMAND_RE.split(pathdef):
if x in COMMANDS:
flt = [x]
if x == "z":
end = True
else:
tks = []
for token in FLOAT_RE.findall(x):
tks.append(token)
if not end:
flt.append(tks)
if flt != [[]]:
yield flt
def round_tk_path(tks):
ptk = tks
new_l = []
for x in ptk:
cmd = x[0]
if cmd!="z":
num = x[1]
nums = []
for y in num:
nums.append( str(f'{ close_half_int( float(y) ):g}') )
new_l.append([cmd, nums])
new_l.append(["z"])
return new_l
def join_tk_path(tks):
tostr = ''
for x in tks:
cmd = x[0]
tostr += cmd
if cmd!="z":
num = x[1]
tostr += ','.join(num)
if_neg_nocomma = tostr.replace(",-", "-")
return if_neg_nocomma
path_d = "M13,9.5H9.7C9.3,9.5,9,9.3,9,8.9c0-0.4,0.3-0.6,0.6-0.6h2.9l0.5,0.5h3l2.4-2.4l-3.7-3.7H9.1c-3.2,0-5.8,2.5-5.8,5.7S5.9,14,9.1,14h3.4c0.3,0,0.6,0.2,0.6,0.6c0,0.4-0.3,0.6-0.6,0.6H8.6l-0.5-0.5h-3l-2.4,2.4l3.7,3.7h6.7c3.2,0,5.8-2.5,5.8-5.7C18.9,12,16.2,9.5,13,9.5z"
tkp = list(tokenize_path(path_d))
rtk = round_tk_path(tkp)
print(join_tk_path(rtk))
# original
# M13,9.5H9.7C9.3,9.5,9,9.3,9,8.9c0-0.4,0.3-0.6,0.6-0.6h2.9l0.5,0.5h3l2.4-2.4l-3.7-3.7H9.1 c-3.2,0-5.8,2.5-5.8,5.7S5.9,14,9.1,14h3.4c0.3,0,0.6,0.2,0.6,0.6c0,0.4-0.3,0.6-0.6,0.6H8.6l-0.5-0.5h-3l-2.4,2.4l3.7,3.7h6.7 c3.2,0,5.8-2.5,5.8-5.7C18.9,12,16.2,9.5,13,9.5z
# result
# M13,9.5H9.5C9.5,9.5,9,9.5,9,9c0,-0.5,0.5,-0.5,0.5,-0.5h3l0.5,0.5h3l2.5,-2.5l-3.5,-3.5H9c-3,0,-6,2.5,-6,5.5S6,14,9,14h3.5c0.5,0,0.5,0,0.5,0.5c0,0.5,-0.5,0.5,-0.5,0.5H8.5l-0.5,-0.5h-3l-2.5,2.5l3.5,3.5h6.5c3,0,6,-2.5,6,-5.5C19,12,16,9.5,13,9.5z
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment