import logging
from sys import argv, exit
logger = logging.getLogger(__name__)
def kinetic_energy(mass, velocity):
return 0.5 * mass * velocity**2
def total_energy(samples):
total = 0
for mass, velocity in samples:
ke = kinetic_energy(mass, velocity)
logger.debug("1/2 * %s * %s ** 2 = %s", mass, velocity, ke)
total += ke
return total
def parse_units(input_str: str) -> tuple[float, str]:
"""Splits units from the end of string, returns truncated input and parsed unit"""
logger.debug("Parsing %s", input_str)
input_str = input_str.lower().replace(" ", "").replace("\t", "")
value, unit = None, None
for unit in (
"kg",
"g",
"km/s",
"m/s",
"km/h",
"feet/s",
):
if input_str.endswith(unit):
value = input_str.replace(unit, "")
break
logger.debug("Parsed value '%s' and unit '%s'", value, unit)
return float(value), unit
def convert_units(value, unit):
if unit == "g":
return value / 1000
elif unit == "kg":
return value
elif unit == "km/h":
return value * 1000 / (60**2)
elif unit == "m/s":
return value
elif unit == "feet/s":
return value * 0.3048
raise ValueError("Unsupported unit type: %s", unit)
def read_data(file_path):
samples = []
with open(file_path, "r") as f:
for line in f:
try:
parts = line.strip().split("@")
mass_value, unit = parse_units(parts[0])
mass = convert_units(mass_value, unit)
logger.info("Conversion Mass %s %s to %s Kg", mass_value, unit, mass)
velocity_value, unit = parse_units(parts[1])
velocity = convert_units(velocity_value, unit)
logger.info(
"Conversion Velocity %s %s to %s m/s",
velocity_value,
unit,
velocity,
)
samples.append((mass, velocity))
except Exception:
logger.error("Failed processing %s ", line.strip())
continue
return samples
if __name__ == "__main__":
logging.basicConfig()
if len(argv) < 2:
logging.critical("Usage: %s filename [--debug]", argv[0])
exit(1)
if "--debug" in argv[1:]:
logger.setLevel(logging.DEBUG)
filename = argv[1]
data = read_data(filename)
print("Total energy:", total_energy(data), "J")