Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Is it possible to do the same using reduce()?

This is part of an assaigment so it needs to be donde using the reduce function (or filter although I don't see it), hence I'd like to know if it's possible.

I have two dicts:

takeOff_Airport = {'LPPD': 4, 'DAAS': 1, 'EDDH': 16, 'LFLL': 17, 'LFPO': 30}
landing_Airport = {'LFPO': 12, 'LPPD': 7, 'UUEE': 11, 'DAAS': 7, 'LFSL': 1}

After applying the follwing code:

airports = (sorted([[k, [v1+landing_Airport[k], v1,landing_Airport[k]]] for k,
                    v1 in takeOff_Airport.items() if k in landing_Airport], 
                    key=lambda kv:kv[1], reverse=True))

I get the expected result:

airports: [['LFPO', 42, 30, 12], ['LPPD', 11, 4, 7], ['DAAS', 8, 1, 7]]

What 'airports' is printing is a list of lists with the common airport names in both dictionaries (landing and takeoff) and adding the sum of each dict value as well as each of the dictionaries [key:value ].

Is it possible to implement the above using some lambda expression in a reduce function? Maybe in a filter?

like image 632
telematics76 Avatar asked Dec 06 '25 05:12

telematics76


1 Answers

It is definitely possible.

The lambda takes as arguments the array x which aggregates the result and the key into one of the airports dictionaries (takeOff_Airport in my example).

If the key exists in the other airport dictionary, then the element formed by [key, sum of each dict value, takeOff value, landing value] is added to the array x. Else, array x is left unchanged.

Pass the lambda into the reduce function, setting the initial value of x to an empty array and it will generate the desired result.

airports = reduce(lambda x, key : x + [[key, takeOff_Airport[key] + landing_Airport[key], takeOff_Airport[key], landing_Airport[key]]] if key in landing_Airport else x, takeOff_Airport, [])

Result:

>>> airports
[['LPPD', 11, 4, 7], ['DAAS', 8, 1, 7], ['LFPO', 42, 30, 12]]
like image 157
M. F. Avatar answered Dec 07 '25 21:12

M. F.