Search code examples
pythonloopssumiteration

Summation of multiple calculations


enter image description here

I'm trying to make the calculation you can see in the screenshot more compact. Is there a way I can write the calculation in only one line?

My problem is that I don't know how to make the summation with all these different frequencies in just one line.


Solution

  • Instead of giving you a direct answer of your question, I recommend you thinking about your data structures to make your life a bit easier. Having two lists which are dependent from each other often make things more complicated than necessary.

    Imagine you first transfer your data structure into one data structure (dict), i.e. something like this:

    data = {
        "25 Hz": {"num": 1},
        "40 Hz": {"num": 2},
        ...
    }
    

    Then you can simply iterate over the values, sum them up and apply log10 at the end:

    result = 0
    for item in data.values():
        result += 10 ** item["num"] * (1/10)
    result = 10 * math.log10(result)
    

    This can also be done as a one-liner as requested:

    10 * math.log10(sum(10 ** item["num"] * (1/10) for item in data.values()))
    

    If you only need a subset from the data, you can filter the rest out, e.g.:

    subset = {"40 Hz", "100 Hz"}
    10 * math.log10(sum(10 ** item["num"] * (1/10) for freq, item in data.items() if freq in subset))
    

    If you're really interested in having a one-liner with the given data structure, then I hope that you have some inspiration from my answer. You will probably end with a double iteration, which is likely to be less performant. A one-liner is imho fine as long it is still understandable. Otherwise I would recommend keeping a simple for iteration or a delegation to a function call.