简体   繁体   中英

How can I write a for loop so that it tests all 5 of my test cases?

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?

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):
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM