I'm writing a Connect Four script. The script takes a list of moves as input ("A_Red, "B_Yellow", "G_Red", etc), which I'm sorting into a matrix. Each nested list represents a column of the board with "A" being the first nested list (or column), and "G" being the last nested list (or column). Moves will then get sorted like so:
A board with some moves will resemble something like:
[ ["Red, "Yellow"], ["Red"], ["Yellow", "Yellow"], [], [], [], [] ]
Once all of the moves are sorted into their respective nested list, I fill each nested list with empty strings ("") to prevent any 'list index out of range errors' with for loops used to perform 4-in-a-row checks.
How can I check if the 4th element (index[3]) of each nested list contains either "Red" or "Yellow" WITHOUT a for loop?
If this condition is True, the diagonal checks will then be performed, and I only need them performed once.
board = [["Red", "Yellow", "Red", "Yellow"], [], [], ["Red", "Yellow", "Red", "Yellow"], [], [], []]
for i in range (0, 7):
if board[i][3]:
# Perform Diagonal Check
The issue with the above code is that I only need the diagonal check to be performed one time when any "Red" or "Yellow" piece is identified in the fourth position in any nested list. With the above for loop, the check will be performed 7 times for each item in the fourth position.
Is it possible to check a range of list positions without going:
if board[0][3] or board[1][3] or board[2][3]... == "Yellow" or "Red": #etc...
forloops? Is there some online curriculum telling you thatforis evil? It's true that there may often be ways of doing something that are more efficient than writing aforloop, but sometimes such a loop is just what's needed. Here, if you're using basic lists, there are better solutions than what you're doing, butforis likely to show up. In most cases where people will tell youforis bad, the alternative tends to be to use something optimised hidden away in a library likenumpy.for- however, it would make more sense to look at the actual problem you're trying to solve, which is deciding whether 4 have been connected yet?forloop if there's a way to stop it from performing diagonal checks for each piece present in the 4th row.