Search code examples
pythonrubylanguage-comparisons

Python equivalent of Ruby's .find


I'm trying to implement the following Ruby method into a Python Method:

CF = {:metre=>{:kilometre=>0.001, :metre=>1.0, :centimetre=>100.0}, :litre=>{:litre=>1.0, :millilitre=>1000.0, :imperial_pint=>1.75975}}

def common_dimension(from, to)
  CF.keys.find do |canonical_unit|
    CF[canonical_unit].keys.include?(from) &&
    CF[canonical_unit].keys.include?(to)
  end
end

Which behaves like:

>> common_dimension(:metre, :centimetre)
=> :metre

>> common_dimension(:litre, :centimetre)
=> nil

>> common_dimension(:millilitre, :imperial_pint)
=> :litre

What is the "Pythonic" way to implement this?


Solution

  • Below code in python for your ruby logic.

    CF={"metre":{"kilometre":0.001, "metre":1.0, "centimetre":100.0}, "litre":{"litre":1.0, "millilitre":1000.0, "imperial_pint":1.75975}}
    
    def common(fr,to):
        for key,value in CF.items():
            if (fr in value) and (to in value):
                return key   
    
    print(common('metre','centimdetre'))
    metre
    print(com('metre','centimdetre'))
    None
    ******************
    
    single line function 
    com = lambda x,y:[key for key,value in CF.items() if (x in value) and (y in value)]
    print(com('metre','centimdetre'))
    ['metre']