Home > Software design >  Condition with number of rows in a database (more than 10 staves or less than 10 staves)
Condition with number of rows in a database (more than 10 staves or less than 10 staves)

Time:03-18

I have a simple code that calculates the arithmetic mean. In the example we calculate the average of 10 elements divided by 10.

But sometimes the elements are less than 10, so obviously I can't divide by 10. So I would like to make sure that if the elements in the list are 10, then you normally calculate the average by dividing by 10 like I did. While if the elements in the list are less than 10, for example there are 7, I would like:

  • count the 7 elements in the list
  • divide by 7 (the elements counted in the list)

How can I correctly write "if rows == 10" and "if rows not 10"? I have no idea. Also "rows.count ()" is the correct code to count rows? Thank you

conn = sqlite3.connect('/database.db')
cursor = conn.cursor()

#arithmetic average
cursor.execute('SELECT x, y FROM table1 WHERE x = ? LIMIT 10;', [combo])
rows= self.cursor.fetchall()
    
if rows == 10:
    arithmetic_average_10 = sum(int(row[0]) for row in rows) / (10) 
        
if rows not 10:
    count_elements = rows.count()
    arithmetic_average_inferior10 = sum(int(row[0]) for row in rows) / (count_elements)

CodePudding user response:

There are two things worth pointing out:

  1. The if statements aren't necessary since your query limits the result to ten rows. You can remove them. This also removes the two differently named variables in the two different branches, which makes it easier to work with the computed average outside of the if blocks.
  2. To get the number of rows in the result, use len().

This gives us the following code snippet:

conn = sqlite3.connect('/database.db')
cursor = connessione.cursor()

#arithmetic average
cursor.execute('SELECT x, y FROM table1 WHERE x = ? LIMIT 10;', [combo])
rows= self.cursor.fetchall()
count_elements = len(rows)
arithmetic_average_inferior10 = sum(int(row[0]) for row in rows) / (count_elements)
  • Related