Skip to content

Instantly share code, notes, and snippets.

@polarities
Created January 21, 2023 14:50
Show Gist options
  • Save polarities/74cb026c0bf6955dc97bc639caa758fe to your computer and use it in GitHub Desktop.
Save polarities/74cb026c0bf6955dc97bc639caa758fe to your computer and use it in GitHub Desktop.
Weight expression
def to_gram(weight, unit:str):
if unit[-1].lower() == 't':
weight *= 1000000 * scale_factor(unit)
unit = 'g'
else:
weight *= scale_factor(unit)
unit = 'g'
return weight, unit
def scale_factor(unit:str):
prefix_dict = dict(
Y=10**24,
Z=10**21,
E=10**18,
P=10**15,
T=10**12,
G=10**9,
M=10**6,
k=10**3,
m=10**-3,
u=10**-6,
μ=10**-6,
n=10**-9,
p=10**-12,
f=10**-15,
a=10**-18,
z=10**-21,
y=10**-24,
)
if len(unit) == 1:
return 1
else:
prefix = unit[0]
return prefix_dict[prefix]
def weight(weight, unit='g'):
prefix = 0
weight, unit = to_gram(weight, unit)
if weight < 1:
unit = [
'g',
'mg',
'μg',
'ng',
'pg',
]
while int(weight) == 0:
if prefix >= len(unit) - 1:
break
prefix += 1
weight *= 1000
print(int(weight))
else:
unit = [
'g',
'kg',
't',
'kt',
'mt',
]
while int(weight / 1000) != 0:
if prefix >= len(unit) - 1:
break
prefix += 1
weight /= 1000
return weight, unit[prefix]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment