1

A rainfall sensor monitors the average rainfall over a year. It records the total once each day per week and all 52 weeks in a year. The program will then

  • Display the total rainfall for each week
  • Display the total for the year
  • The smallest and largest amount of rainfall in a single week.

The following program reads data from a CSV file and then populates the array one row at a time. So far, the program can calculate the total rainfall for the year by traversing each row of the array at a time and incrementing a total. I am not sure how to find the total rainfall from each week with the smallest and largest amount of rainfall that week.

CODE

import random

#global variables
rows = 52
cols = 7

def initArray():
    newArray = [[None]*cols for i in range(rows)]
    return newArray

def populateArray(arrayname,filename):
    rowcounter = 0
    colcounter = 0
    with open(filename) as readfile:
        line = readfile.readline().rstrip('\n')
        while line:
            #read the line of a file
            items = line.split(",")
            print("Items = ", items)
            #reset the colcounter to ensure first item is placed
            #at first position in the 2D array
            colcounter = 0
            #for the length of the array
            for x in range(len(items)):
                #place the new values into the array a row at a time
                arrayname[rowcounter][colcounter] = int(items[colcounter])
                #increment the column counter
                colcounter += 1
            #increment the row counter
            rowcounter += 1
            line = readfile.readline().rstrip('\n')

    return arrayname

def yearly(arrayname):
    total = 0
    for x in range(len(arrayname)):
        for y in range(len(arrayname[x])):
            total += arrayname[x][y]

    return total

rainfall = initArray()
rainfall = populateArray(rainfall,"rainfall.csv")
total = yearly(rainfall)

print("The total rainfall for the year was",str(total))

output:

Items =  ['2', '16', '10', '2', '12', '9', '9']
Items =  ['2', '29', '17', '16', '13', '18', '7']
Items =  ['22', '15', '27', '19', '6', '26', '11']
Items =  ['21', '7', '18', '4', '14', '14', '2']
Items =  ['6', '30', '12', '4', '26', '22', '11']
Items =  ['21', '16', '14', '11', '28', '20', '3']
Items =  ['19', '10', '22', '18', '30', '9', '27']
Items =  ['8', '15', '17', '4', '11', '16', '6']
Items =  ['19', '17', '16', '6', '18', '18', '6']
Items =  ['2', '15', '3', '25', '27', '16', '11']
Items =  ['15', '5', '26', '24', '24', '30', '5']
Items =  ['15', '11', '16', '22', '14', '23', '28']
Items =  ['25', '6', '7', '20', '26', '18', '16']
Items =  ['5', '5', '21', '22', '24', '16', '5']
Items =  ['6', '27', '11', '8', '24', '1', '16']
Items =  ['28', '4', '1', '4', '3', '19', '24']
Items =  ['19', '3', '27', '14', '12', '24', '0']
Items =  ['6', '3', '26', '15', '15', '22', '26']
Items =  ['18', '5', '0', '14', '15', '7', '26']
Items =  ['10', '5', '12', '22', '8', '7', '11']
Items =  ['11', '1', '18', '29', '6', '9', '26']
Items =  ['3', '23', '2', '21', '29', '15', '25']
Items =  ['5', '7', '1', '6', '15', '18', '24']
Items =  ['28', '11', '0', '6', '28', '11', '26']
Items =  ['4', '28', '9', '24', '11', '13', '2']
Items =  ['6', '2', '14', '18', '20', '21', '1']
Items =  ['20', '29', '22', '21', '11', '14', '20']
Items =  ['28', '23', '14', '17', '25', '3', '18']
Items =  ['6', '27', '6', '20', '19', '5', '24']
Items =  ['25', '3', '27', '22', '7', '12', '21']
Items =  ['12', '22', '8', '7', '0', '11', '8']
Items =  ['8', '25', '1', '6', '21', '23', '0']
The total rainfall for the year was 5344

CSV Data

0,0,30,2,21,13,23
29,3,29,30,7,8,25
26,5,26,13,4,13,4
22,30,13,15,15,0,2
3,12,11,10,17,0,15
8,13,11,24,30,24,27
22,18,2,29,11,13,18
15,1,29,23,18,7,0
23,27,3,7,13,14,28
6,25,24,14,20,23,5
24,29,26,22,0,9,18
22,27,22,20,24,29,21
23,13,14,4,13,1,21
25,21,21,6,28,17,19
4,6,11,10,21,1,5
11,7,22,11,10,24,15
25,11,23,3,23,8,3
22,23,0,29,15,12,5
21,11,18,22,1,4,3
11,10,3,1,30,14,22
2,16,10,2,12,9,9
2,29,17,16,13,18,7
22,15,27,19,6,26,11
21,7,18,4,14,14,2
6,30,12,4,26,22,11
21,16,14,11,28,20,3
19,10,22,18,30,9,27
8,15,17,4,11,16,6
19,17,16,6,18,18,6
2,15,3,25,27,16,11
15,5,26,24,24,30,5
15,11,16,22,14,23,28
25,6,7,20,26,18,16
5,5,21,22,24,16,5
6,27,11,8,24,1,16
28,4,1,4,3,19,24
19,3,27,14,12,24,0
6,3,26,15,15,22,26
18,5,0,14,15,7,26
10,5,12,22,8,7,11
11,1,18,29,6,9,26
3,23,2,21,29,15,25
5,7,1,6,15,18,24
28,11,0,6,28,11,26
4,28,9,24,11,13,2
6,2,14,18,20,21,1
20,29,22,21,11,14,20
28,23,14,17,25,3,18
6,27,6,20,19,5,24
25,3,27,22,7,12,21
12,22,8,7,0,11,8
8,25,1,6,21,23,0
4
  • as you iterate to find the sum, you could keep track of the minimum and maximum values found so far or (somewhat lazily, but there's not a lot of data) pack values into a new list for further actions and call min() and max() on that list Commented Jun 15, 2022 at 23:06
  • 3
    Are you asking how to find the min and max of each row? That is exactly the same as finding the min and max of any list (you're going to have to convert them strings to integers first). Then do this on all rows. Alternatively, consider using a library such as numpy or pandas. Commented Jun 15, 2022 at 23:06
  • 3
    indeed - Pandas CSV loading is very powerful and will provide a DataFrame object that will let you operate on rows or the entire collection at once (such as finding the absolute min and max)! however, it's a very large dependency, which you might see benefit in using the powerful features of or conversely have trouble installing in some restricted environment Commented Jun 15, 2022 at 23:08
  • Also note that you need to provide a minimal reproducible example that is minimal and limited to only the question you're asking about. Since you're asking how to find the min and max, the part of your code that parses the CSV file is irrelevant, and could be replaced by a hard-coded list-of-lists representing the first few rows of your csv. Commented Jun 15, 2022 at 23:10

2 Answers 2

2

I've seen some suggestions for pandas, which would also work well, but for something simple like this you may just want to use numpy:

import numpy as np

rainfall = np.loadtxt(filename, delimiter=',')
total = rainfall.sum()

print(f"The total rainfall for the year was {total:.0f}")
print(f"Overall Min: {rainfall.min()}")
print(f"Overall Max: {rainfall.max()}")
print("Weekly Sums:")
print(rainfall.sum(axis=1))
print("Weekly Mins:")
print(rainfall.min(axis=1))

Output:

The total rainfall for the year was 5344
Overall Min: 0.0
Overall Max: 30.0
Weekly Sums:
[ 89. 131.  91.  97.  68. 137. 113.  93. 115. 117. 128. 165.  89. 137.
  58. 100.  96. 106.  80.  91.  60. 102. 126.  80. 111. 113. 135.  77.
 100.  99. 129. 129. 118.  98.  93.  83.  99. 113.  85.  75. 100. 118.
  76. 110.  91.  82. 137. 128. 107. 117.  68.  84.]
Weekly Mins:
[ 0.  3.  4.  0.  0.  8.  2.  0.  3.  5.  0. 20.  1.  6.  1.  7.  3.  0.
  1.  1.  2.  2.  6.  2.  4.  3.  9.  4.  6.  2.  5. 11.  6.  5.  1.  1.
  0.  3.  0.  5.  1.  2.  1.  0.  2.  1. 11.  3.  5.  3.  0.  0.]
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. Can you explain to me what is wrong with the following code? why it's giving all 0s? def findminweekly(newarray): minimum = [int(1000000000)] * 52 for x in range(len(newarray)): for y in range(len(newarray[x])): for i in range(len(newarray)): if newarray[x][y] < minimum[i]: minimum[i] = newarray[x][y] return minimum
There's absolutely no way I can diagnose that code in it's current form. I'd suggest taking what you've learned here from comments and this answer, and making a new question to address that issue.
-1
from itertools import chain

array_max = max(chain(*arrayname))
array_min = min(chain(*arrayname))

Note that if you didn't convert the values to int first, then min and max will be the lowest and highest individual digits, because min and max will be checking character by character in the strings.

(edited to clarify what happens if you didn't convert to int)

8 Comments

Why will you always get min = 0 and max = 9? Even if there are no zeros or nines in the list?
well, ok, you won't ALWAYS get 0 and 9 if your dataset is small or oddly distributed, but if you didn't convert everything to int, then min and max will be checking the character values instead, so the lowest you could have is 0, and the highest you could have is 9. As an example, check min("95134627846235976416548") and you'll get 1
@nigh_anxiety you're probably seeing unusual results from Python treating strings as being iterable (for example min("1,2,3,4") == ',' ???: this is because "," < "1"), while passing the input more cleanly (perhaps via a generator min(int(x) for x in line.split(","))) will give a better result
OP has a list of lists. Chaining these gives you a "flattened" "list", and getting the max of this will return the max string in this flattened list. max("1234567890") returns 9 because the input string is an iterable itself. Even though your answer is correct for OP's case, your explanation of what happens if you don't convert to ints first is wrong. (although OP did convert to ints before appending to the list-of-lists, so I guess it's a moot point)
I tested with his exact list of lists without converting and it gave me "0" and "9" as my min and max
|

Your Answer

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.