MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / convert_speed

Function convert_speed

conversions/speed_conversions.py:25–65  ·  view source on GitHub ↗

Convert speed from one unit to another using the speed_chart above. "km/h": 1.0, "m/s": 3.6, "mph": 1.609344, "knot": 1.852, >>> convert_speed(100, "km/h", "m/s") 27.778 >>> convert_speed(100, "km/h", "mph") 62.137 >>> convert_speed(100, "km/h", "knot")

(speed: float, unit_from: str, unit_to: str)

Source from the content-addressed store, hash-verified

23
24
25def convert_speed(speed: float, unit_from: str, unit_to: str) -> float:
26 """
27 Convert speed from one unit to another using the speed_chart above.
28
29 "km/h": 1.0,
30 "m/s": 3.6,
31 "mph": 1.609344,
32 "knot": 1.852,
33
34 >>> convert_speed(100, "km/h", "m/s")
35 27.778
36 >>> convert_speed(100, "km/h", "mph")
37 62.137
38 >>> convert_speed(100, "km/h", "knot")
39 53.996
40 >>> convert_speed(100, "m/s", "km/h")
41 360.0
42 >>> convert_speed(100, "m/s", "mph")
43 223.694
44 >>> convert_speed(100, "m/s", "knot")
45 194.384
46 >>> convert_speed(100, "mph", "km/h")
47 160.934
48 >>> convert_speed(100, "mph", "m/s")
49 44.704
50 >>> convert_speed(100, "mph", "knot")
51 86.898
52 >>> convert_speed(100, "knot", "km/h")
53 185.2
54 >>> convert_speed(100, "knot", "m/s")
55 51.444
56 >>> convert_speed(100, "knot", "mph")
57 115.078
58 """
59 if unit_to not in speed_chart or unit_from not in speed_chart_inverse:
60 msg = (
61 f"Incorrect 'from_type' or 'to_type' value: {unit_from!r}, {unit_to!r}\n"
62 f"Valid values are: {', '.join(speed_chart_inverse)}"
63 )
64 raise ValueError(msg)
65 return round(speed * speed_chart[unit_from] * speed_chart_inverse[unit_to], 3)
66
67
68if __name__ == "__main__":

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected