0

Ok code created which outputs a table like this:

[['              ' '     Scarface ' '     Godfather' '        Avatar']
['Al Pachino    ' '             1' '             1' '            -1']
['Marlon Brando ' '            -1' '             1' '            -1']
['De Niro       ' '            -1' '             1' '            -1']
['Sigorny Weaver' '            -1' '            -1' '             1']]

How do I get the average of a table column by writing a function whose arguments are a table of integer numbers A and a positive integer number i. The function should return the average of non-negative entries of the column i of A.

I want to do this in the most simple readable code which later I can explain to kids.

Thanks Jemma

3
  • Have you tried something? Where is your code? Commented Nov 28, 2016 at 15:51
  • Could you provide a full example (using the data of your table) of what you want ? Commented Nov 28, 2016 at 16:04
  • What is a "table?" What you have here is a list of lists where each sublist contains a single string. Commented Nov 28, 2016 at 16:05

1 Answer 1

2

To get average with formula <ONLY-POSITIVE-VALUES> / <ALL-INTEGER-COLUMS>

data = [
    ['              ', '     Scarface ', '     Godfather', '        Avatar'],
    ['Al Pachino    ', '             1', '             1', '            -1'],
    ['Marlon Brando ', '            -1', '             1', '            -1'],
    ['De Niro       ', '            -1', '             1', '            -1'],
    ['Sigorny Weaver', '            -1', '            -1', '             1']
]

def compute_average(row):
    average = 0
    count   = 0
    for column in row:
        count += 1
        try:
            value = int(column)
        except ValueError:
            continue

        if value > 0:
            average += value

    return float(average) / count

for row in data[1:]:
    print compute_average(row)

If you need formula like <ONLY-POSITIVE-VALUES> / <ALL-POSITIVE-VALUES-COLUMS> just move the count += 1 line from the top of for loop to the if value > 0 statement.

The try / except part is only because Python raise error when you try to parse a non-integer string in integer, it allow you to fetch any data and just skip non-integer ones.

Sign up to request clarification or add additional context in comments.

Comments

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.