I am learning python using STEPIK and I am facing this:
I want on every iteration of the inside for loop sum the values of predicted_growth
list with the value of cases
list, save it in some temporary variable and print it. Click on the link for the full challenge.
This is my code so far:
def predict_cases(cases, predicted_growth): print() result = [] for i in range(len(cases)): for j in range(len(predicted_growth)): result = cases[i] + predicted_growth[j] print(result, end = " ") print() cases = [12508, 9969, 310595, 57409] predicted_growth = [100, 200, 300] predict_cases(cases, predicted_growth)
This is the output of the function I should be getting:
[12608, 10069, 310695, 57509] [12808, 10269, 310895, 57709] [13108, 10569, 311195, 58009]
Instead I am getting this:
12608 12708 12808 10069 10169 10269 310695 310795 310895 57509 57609 57709
Advertisement
Answer
You can use a loop with an inner list comprehension.
def predict_cases(cases, predicted_growth): res = [] # this will hold the results for growth_rate in predicted_growth: # outer loop to iterate the growth rate prev = res[-1] if res else cases # get the previously computed result, if there is no such result get initial cases (`cases`) as previously computed result res.append([growth_rate + i for i in prev]) # list comprehension to add the current growth rate(`growth_rate`) to the previous cases for result in res: # iterate through `res` list print(result) # print the result cases = [12508, 9969, 310595, 57409] predicted_growths = [100, 200, 300] predict_cases(cases, predicted_growths)
Output
[12608, 10069, 310695, 57509] [12808, 10269, 310895, 57709] [13108, 10569, 311195, 58009]