1

I am supposed to work out the periodic investment amount given the target wealth.

This is my user defined code:

def contribution_calculator(target_wealth, rate, duration, periodicity):
    inv_amt = -npf.pmt(rate/100/periodicity, duration*periodicity, 0, target_wealth)
    return inv_amt

These are my 5 test cases which I have put them into their respective list.

target_wealth = [1000000, 1000000, 3000000, 3000000, 2000000]

rate = [2.5, 2.5, 0.5, 4.0, 3.0]

duration = [25, 12, 25, 25, 10]

periodicity = [12, 1, 12, 12, 2]

For example, the values for test case 1 are 1000000, 2.5, 25, 12.

How can I write a for loop such that it will test all the 5 given test cases?

Psidom
  • 209,562
  • 33
  • 339
  • 356
  • Do you also want to test the combination, for example: 2000000, 2.5, 25, 12 ? – mpx Aug 14 '21 at 06:46
  • @balandongiv yes please! I would like to test my other combinations, such as 1000000, 2.5, 12, 1 for test case 2, and 3000000, 0.5, 25, 12 for test case 3. Is there a way I could do a for loop to test all these cases using my user defined function contribution_calculator? – Hidden Angle Aug 14 '21 at 06:57
  • 1
    Ah, if you want to test all combinations, you need `itertools.product` rather than `zip` – Jiří Baum Aug 14 '21 at 07:19
  • @sabik i see! thanks a lot! – Hidden Angle Aug 14 '21 at 09:42

1 Answers1

4

You can use zip() and tuple unpacking, like this:

for tw, r, d, p in zip(target_wealth, rate, duration, periodicity):
    ...

Perhaps rename the lists, so you can use the full variable names:

for target_wealth, rate, duration, periodicity in zip(target_wealths, rates, durations, periodicities):
    ...

PS: If you want to test all combinations, rather than corresponding values, you can use itertools.product instead of zip:

import itertools
for target_wealth, rate, duration, periodicity in itertools.product(target_wealths, rates, durations, periodicities):
    ...
Jiří Baum
  • 6,697
  • 2
  • 17
  • 17