Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Convert Units Between Measures

MediumPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Convert Units Between Measures. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Granular field data may report measurements such as acres, hectares, feet, and meters. Given known conversion relationships, implement a function that converts a value from one unit to another, even when no direct relationship is provided.

Model each unit as a graph node. A conversion A -> B with factor f means one unit of A equals f units of B. The reverse relationship has factor 1 / f. Return None when the source and target units are disconnected.

Formal Specification

Implement convert_units(value, source, target, conversions).

  • value is a real number.
  • source and target are non-empty unit-name strings.
  • conversions is a list of three-element lists [unit_a, unit_b, factor], where factor is positive and means 1 unit_a = factor unit_b.
  • Return a numeric value representing value in target units. Return value unchanged when source == target. Return None if no path exists.
  • Assume conversion relationships are mutually consistent when multiple paths exist.

Constraints

  • 1 <= len(conversions) <= 10^4
  • Each conversion contains two unit names and one positive factor
  • 0 < factor <= 10^12
  • Conversion factors and values may be fractional
  • Return None when source and target are disconnected

Function Signature

def convert_units(value, source, target, conversions):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output