Welcome to the CSC Q&A.
Get help and give help!
Write great code!
It is our choices... that show what we truly are, far more than our abilities.

Categories

+6 votes

Does anyone have any tips on how to add together the specific column that you want?
i got the code to work for the 2x2 lists but im getting "list index out of range" or slightly wrong numbers for the longer lists

asked in CSC201 Spring 2021 by (8 points)
0

I got a similar error in the routine practice problems and I solved them by working backwards instead of forward. When you're altering the list(i.e adding, removing or inserting a character), the index gets altered too when you work forward.

2 Answers

+5 votes
 
Best answer

When you are accessing a grid/matrix, the second index number is the column:

aMatrix[row][column]

So to access a specific column, each time through the loop the second index number should be the column you want to access. So it becomes

aMatrix[row][desiredColumnNum]

With [row] changing each loop and [desiredColumnNum] staying the same.
Does that make sense?

answered by (8 points)
selected by
+3 votes

To take a step back from the original question, which Furby already answered pretty well... what are some general strategies we can use to solve a problem like this when we get stuck?

Believe it or not, there are some really excellent general problem solving strategies, as outlined in George Polya's amazing book: How to Solve It (https://en.wikipedia.org/wiki/How_to_Solve_It). Much of his advice about solving math problems also pertains to computer science problems.

A strategy that I commonly use is: use an example.
That is, think carefully through the steps needed to solve a specific instance of the problem (e.g. with numbers instead of variables).

Suppose you have a 5x5 list of lists named numberTable , and our desired column number is 3.

Then we would need to access:

numberTable[0][3]
numberTable[1][3]
numberTable[2][3]
numberTable[3][3]
numberTable[4][3]

and add all of those up.

(Another of George Polya's strategies is to draw a picture/diagram, which would also be helpful in visualizing column index 3 in a 5x5 array... but it's hard for me to insert such a diagram here. It would be pretty easy to sketch on paper though!)

Notice that the first index is changing, but the 2nd index is not, because we always want column #3. That means we'll want a FOR LOOP to go from 0 through 4, to represent each row index, while we will continue to use 3 (our desired column index) for the 2nd index into the table.

If this doesn't lead naturally to code yet, try tracing through a second example, with a 4x4 table where we want to add up column 0.

answered by (186 points)
...