Home > Blockchain >  How to return multiple values in a list
How to return multiple values in a list

Time:08-03

I am a new programmer and I cant figure out how to return two values in a list. my task that I am working on is this:

You are given the data of weekly Covid-19 cases in your region and want to report some basic information given the data. In particular, you are interested in calculating the number of peaks, which is defined as a week where there are strictly more cases than in the week immediately preceding and in the week immediately after. The first and last week cannot be a peak.
Write a function named “calc_peaks” and with a single input of a list covid_cases that does the following:

  1. Prints out the average cases per week as an integer, rounded down.
  2. Prints out the maximum number of cases that ever occurred in a week.
  3. Returns a list of the indices of the input list that correspond to peaks
  4. (Bonus) Prints out the average number of cases during a week that is a peak.

For example, if you call the function as calc_peaks([100, 300, 200, 100, 600, 300]), it should print 266 as the average number of cases and 600 as the maximum. Then, it should [1, 4] as the list of peaks. For the bonus task, it should print 450 as the average number of cases in a week that is a peak. Here is my code:

for i in range(0,len(covid_cases)):
    if (covid_cases[i]>=covid_cases[i-1] and covid_cases[i]>=covid_cases[i 1]):
      return i
print(calc_peaks([100,300,200,100,600,300]))

When I print this it returns 1 for the peaks. How do I make it so it returns 1 and 4? Help gladly appreciated :)

CodePudding user response:

When your function returns something, it stops. In your case when the function processes the first value, it returns the value and stops further execution. You need to use yield which gives you a generator and a more pythonic way of solving this problem.

CodePudding user response:

"i" here is a variable that stores a single value. To achieve the required result you need:

  • a Data Structure that can store multiple values

Once you are done storing all values, you need to return the same. Please refer tweaked code below to solve your problem:

peaks=[]
def calc_peaks(covid_cases):
  for i in range(0,len(covid_cases)):
    if (covid_cases[i]>=covid_cases[i-1] and covid_cases[i]>=covid_cases[i 1]):
      peaks.append(i)
  return peaks
print(calc_peaks([100,300,200,100,600,300]))
  • Related