Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 421
Baxter Avatar asked Dec 07 '25 18:12

Baxter


2 Answers

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']
like image 150
Jeevan Chaitanya Avatar answered Dec 09 '25 16:12

Jeevan Chaitanya


Other option both for Ruby and Python.

For Ruby:

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

from = :litre
to = :millilitre
cf.select { |k, v| ([from, to] - v.keys).empty? }.keys
#=> [:litre]

For Python:

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

_from = 'millilitre'
_to = 'imperial_pint'
res = [ k for k, v in CF.items() if not bool(set([_from, _to]) - set(v.keys())) ]
#=> ['litre']
like image 20
iGian Avatar answered Dec 09 '25 15:12

iGian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!