1

I have been asked to find the sum of the first value in each column in a nested list. How do I do this without using imports or the sum function?

 def column_sums(square):
    """Returns the sum of the columns"""

    result = []
    i = 0
    for element in square:
        n = 0
        for item in element:
            if item == element[n]:
                i = i + item
        n = n + 1
    result.append(i)
    i = 0
    return result

square = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12],
    [13, 14, 15, 16]
]
print(column_sums(square))

This is what I have come up with but it only returns the value of the first column. How can I get the sum of all the columns set out like this?:

[28, 32, 36, 40]
1
  • Can you be more specific about what the issue is? Have you written any pseudocode/design? Commented May 1, 2020 at 9:46

3 Answers 3

2

For a purely loop based approach without any built-ins:

def column_sums(square):
    result = [0] * len(square[0])
    for row in square:
        for i in range(len(result)):
            result[i] += row[i]
    return result

The following uses the zip(*...) transpositional pattern:

def column_sums(square):
    result = []
    for col in zip(*square):
        total = 0
        for num in col:
            total += num
        result.append(total)
    return result

square = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12],
    [13, 14, 15, 16]
]
print(column_sums(square))
# [28, 32, 36, 40]

Note that you get the columns by zipping the rows. If you could use sum and all other built-ins, the following would be the shortest:

print(list(map(sum, zip(*square))))
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, that really helped. I didn't know about zip(* )!
1

Use this:

def column_sums(square):
    result = dict.fromkeys(len(square), 0)
    for i, v in enumerate(zip(*square)):
        for x in v:
            result[i] += x
    return result

square = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12],
    [13, 14, 15, 16]
]
print()

Or with sum you can actually just use:

square = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12],
    [13, 14, 15, 16]
]
print(column_sums(square))

3 Comments

"How do I do this without [...] the sum function?"
Nope, wasn't me
sum is disallowed as per OP.
1

Here you go with the simplest sol that came to my mind without using any fancy stuff.

def column_sums(square):
    """Returns the sum of the columns"""

    result = [0,0,0,0]
    for element in square:

        for i,item in enumerate(element):
                result[i] = result[i] + item   
    return result

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.