Python Forum
How to print all iterations of min and max for a 2D list
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to print all iterations of min and max for a 2D list
#1
Hello, I am new to Python and need help with my program. I need to create a program that assigns random integers in between 0 and 4 to each month of the year. Next I need to calculate the sum and average. Then I need to display all iterations of the lowest rainfall months and the highest rainfall months, which is where I'm struggling. I specifically need help with my function called find_minmax. Does anyone know where I'm going wrong? My program:

import random

#define monthly rainfall function
def monthlyRainfall():

  #assign diff random numbers numbers to each month between the values of zero and four
  rainfall_jan=random.randint(0, 4)
  rainfall_feb=random.randint(0, 4)
  rainfall_mar=random.randint(0, 4)
  rainfall_apr=random.randint(0, 4)
  rainfall_may=random.randint(0, 4)
  rainfall_jun=random.randint(0, 4)
  rainfall_jul=random.randint(0, 4)
  rainfall_aug=random.randint(0, 4)
  rainfall_sep=random.randint(0, 4)
  rainfall_oct=random.randint(0, 4)
  rainfall_nov=random.randint(0, 4)
  rainfall_dec=random.randint(0, 4)
  
  #create two dimensional list for the months and rainfall
  monthly_rainfall = [ ['January',rainfall_jan],
                      ['February', rainfall_feb],
                      ['March', rainfall_mar],
                      ['April', rainfall_apr],
                      ['May', rainfall_may],
                      ['June', rainfall_jun],
                      ['July', rainfall_jul],
                      ['August', rainfall_aug],
                      ['September', rainfall_sep],
                      ['October', rainfall_oct],
                      ['November', rainfall_nov],
                      ['December', rainfall_dec] ] 

  #calculate the total amount of rainfall 
  total=(rainfall_jan+rainfall_feb+
        rainfall_mar+rainfall_apr+
        rainfall_may+rainfall_jun+
        rainfall_jul+rainfall_aug+
        rainfall_sep+rainfall_oct+
        rainfall_nov+rainfall_dec)

  #calculate average rainfall
  average=total / 12

  #calculate the minimum and maximum rainfall 
  #print all iterations of month only
  def find_minmax():
    lowest = min(monthly_rainfall, key=lambda x: (x[1],x[0]))      
    highest = max(monthly_rainfall, key=lambda x: (x[1],x[0]))
    minList = []
    maxList = []
    strMin = ''
    strMax = ''
    for row in range(len(monthly_rainfall)):
        for col in range(len(monthly_rainfall[row])):
            if col==1 and monthly_rainfall [row][col]==lowest:
                minList.append(monthly_rainfall[row][0])
            elif col==1 and monthly_rainfall[row][col]==highest:
                maxList.append(monthly_rainfall[row][0])
    strMin = ', '.join(minList)
    strMax = ', '.join(maxList)
    print('Lowest rainfall: ', strMin)
    print('Highest rainfall: ', strMax)

  #display ascending rainfall by month
  def ascend():
    monthly_rainfall.sort(key=lambda x:(x[1]))
    for ascend in monthly_rainfall:
      print(*ascend)


  #print the two dimensional list 
  print(monthly_rainfall)
  
  #print the table function
  table()

  #print the two dimensional list with each nested list on a new line
  for row in monthly_rainfall:
    for cell in row:
        print(cell, end=' ')
    print()
  
  #print horizontal dashes
  divider()

  #print the total rainfall
  print('Total rainfall:', total)

  #print the average rainfall and format number to two decimal places
  print('Average rainfall:', format(average, ',.2f'))

  #call the min/max function
  find_minmax()

  divider()

  #call ascend function
  print('Months sorted by rainfall')
  print('Ordered by calendar month')
  divider()
  ascend()


#create the divider (horizontal dashes)
def divider():
  print('----------------')

#create table function
def table():
  print()
  print('Month | Rainfall')
  divider()


def main():
  monthlyRainfall()


main()
Reply
#2
I'm not sure where you are in your course,
but I think that you only need 25 lines for this excrcise and not 120.
With a for loop you can make a list of 12 months' rainfall.
Index 0 = always January, 11 = December.
Don't bother about the month names, make a separate list (or set) for reporting.
Then it becomes simple: sum(), min() max() are built in.
If you know the min(), iterate over the list to find all the months. same for max().
Paul
buran likes this post
Reply
#3
I prefer approach where Python is used as programming language and not as typewriter (DRY - Don't Repeat Yourself).

This is homework and all, however from conditions and terms presented here is not obvious is 2D list is requirement or design desicion. It could be much simpler to keep month names and rainfalls in different lists.

There is no need to create variables for month rainfalls. You don't need to sum manually.

To get month names, instead of typing one can use built-in calendar:

>>> import calendar
>>> months = calendar.month_name[1:]
>>> months
['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']


To get random rainfalls instead of typing repeating lines you can just create list with values:

rainfall = [random.randint(0, 4) for month in months]
It is easy to get min and max values and sum from rainfall list.

If needed, it is quite simple to create list of tuples out of two lists:

data = [*zip(months, rainfall)]

# alternatively, if list of list is needed:

data = [[*pair] for pair in zip(months, rainfall)] 
In order to get all months which have minimum (or maximum) rainfall one can find indices of items in rainfall list where item value is equal to minimum (or maximum) value and return items on same index in months list.
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#4
Thank you, perfringo! This was super helpful! I was able to simplify my code and get my min and max to work. Dance

(Nov-10-2020, 10:30 AM)perfringo Wrote: I prefer approach where Python is used as programming language and not as typewriter (DRY - Don't Repeat Yourself).

This is homework and all, however from conditions and terms presented here is not obvious is 2D list is requirement or design desicion. It could be much simpler to keep month names and rainfalls in different lists.

There is no need to create variables for month rainfalls. You don't need to sum manually.

To get month names, instead of typing one can use built-in calendar:

>>> import calendar
>>> months = calendar.month_name[1:]
>>> months
['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']


To get random rainfalls instead of typing repeating lines you can just create list with values:

rainfall = [random.randint(0, 4) for month in months]
It is easy to get min and max values and sum from rainfall list.

If needed, it is quite simple to create list of tuples out of two lists:

data = [*zip(months, rainfall)]

# alternatively, if list of list is needed:

data = [[*pair] for pair in zip(months, rainfall)] 
In order to get all months which have minimum (or maximum) rainfall one can find indices of items in rainfall list where item value is equal to minimum (or maximum) value and return items on same index in months list.
Reply
#5
Thanks, Paul! Much appreciated. I used your suggestion of a for loop and got exactly what I needed.

(Nov-10-2020, 09:52 AM)DPaul Wrote: I'm not sure where you are in your course,
but I think that you only need 25 lines for this excrcise and not 120.
With a for loop you can make a list of 12 months' rainfall.
Index 0 = always January, 11 = December.
Don't bother about the month names, make a separate list (or set) for reporting.
Then it becomes simple: sum(), min() max() are built in.
If you know the min(), iterate over the list to find all the months. same for max().
Paul
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Help with creating loops and Iterations for ISO Weeks abecruz92 1 1,303 Dec-29-2022, 12:33 PM
Last Post: Yoriz
  Many iterations for loop question adesimone 9 1,816 Nov-12-2022, 07:08 PM
Last Post: deanhystad
  Why does this function print empty list? hhydration 1 1,524 Oct-28-2020, 02:03 AM
Last Post: deanhystad
  List of Objects print <__main. Problem Kol789 10 3,489 Jul-21-2020, 09:37 AM
Last Post: DeaD_EyE
  How can I print the number of unique elements in a list? AnOddGirl 5 3,246 Mar-24-2020, 05:47 AM
Last Post: AnOddGirl
  Print The Length Of The Longest Run in a User Input List Ashman111 3 3,177 Oct-26-2018, 06:56 PM
Last Post: gruntfutuk

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020