Search code examples
pythonpython-3.xlistcomparison

How to compare corresponding elements in list/array/dict in python


Suppose you have two lists (or any type of grouping, it doesn't matter which one) containing variables that represent milk, eggs, and flour. For instance:

have(milk, eggs, flour)

and

need(milk, eggs, flour)

How might you go about determining whether each element >=, ==, or <= its counterpart in the other list so that you can return some indication as to whether there is or is not enough of each ingredient to make a proverbial cake or if there is enough to make more than one?

I'd really prefer not to write War and Peace for the sake of 3 comparisons. Any help is appreciated.


Solution

  • Asssuming input as the following

    milk=200
    eggs=10
    flour=1000
    
    milk_reqd=100
    eggs_reqd=5
    flour_reqd=2000
    
    have=[milk, eggs, flour]
    need=[milk_reqd, eggs_reqd, flour_reqd]
    

    Solution

    import numpy as np
    have=np.array(have)
    need=np.array(need)
    

    Now you can perform all operations like

    need>have
    

    Or

    need<=have
    

    Or

    need-have
    

    To get the number of cakes that can be made

    n_cakes=int(min(have/need))