0

I created a function which updates the single list by adding the interest rate.

def first(lst, rate):
 for i in range(len(lst)):
 lst[i] += lst[i] * rate[i]

My question is, how to use this function to update two dimensional list by adding the interest rate?

For example:

lst2 = [[25, 10, 300], [7, 30, 80], [7, 530, 24],[65, 30, 2]]
rate = [0.5, 0.02, 0.15]
>>> for i in lst2:
 print(i)
[37.5, 10.2, 345.0]
[10.5, 30.6, 92.0]
[10.5, 540.6, 27.6]
[97.5, 30.6, 2.3]

My code:

def second(lst2, rate):
 for x in lst2:
 for y in x:
 lst2[x][y] += first(lst2[x][y],rate[x])

Any help will be much appreciated. Thanks

Cat Plus Plus
131k27 gold badges205 silver badges226 bronze badges
asked Nov 14, 2011 at 3:55
0

3 Answers 3

1

This situation is kind of strange, because you're completely relying on the functions having side-effects instead of returning values. However, here's a solution:

def second(lst2, rate):
 for i in range(len(lst2)):
 first(lst2[i], rate)
answered Nov 14, 2011 at 4:16
Sign up to request clarification or add additional context in comments.

Comments

0

Short answer: this is what numpy is for.

import numpy
lst2 = numpy.array( [ ..as above.. ])
rate = numpy.array( [.. as above.. ])
lst_with_interest = lst2 + lst2*rate[numpy.newaxis,:]

Without numpy, it's possible lots of different ways, mostly depending on how general you want the solution to be. A good general way is to write something which does a single dimension, and looks at its parameters to see if the rate is a list or a single number; see the zip() function for dealing with the list case.

answered Nov 14, 2011 at 4:12

Comments

0

Easy way is to say

for i in range(len(lst2)):
 first(lst2[i], rate)

lst2 will then contain [[37.5, 10.2, 345.0], [10.5, 30.6, 92.0], [10.5, 540.6, 27.6], [97.5, 30.6, 2.3]]

answered Nov 14, 2011 at 4:18

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.