Checking if the numbers in a list in a list are in a certain range

90 Views Asked by At

So I have a list with multiple list in it which represent something like coordinates. In my case they are positions on a chessboard. The list would look something like this: [(3, 3), (4, 3), (5, 3), (6, 3), (3, 4), (4, 4), (5, 4), (6, 4), (3, 5), (4, 5)] This is just an example. My problem is, I need to check if any of these coordiantes are out of a certain range, on the chessboard, for example 1-8. Unfortunately i could only get the all() command to work with a list which just consists of numbers and not a list with lists of numbers.

2

There are 2 best solutions below

1
On

you can import numpy module and use function max

import numpy as np

>>> l =np.array([(3, 3), (4, 3), (5, 3), (6, 3), (3, 4), (4, 4), (5, 4), (6, 4), (3, 5), (4, 5)])

>>> l.max()
6
0
On

Then iterate through each of the individual coordinates:

>>> coords = [(3, 3), (4, 3), (5, 3), (6, 3), (3, 4), (4, 4), (5, 4), (6, 4), (3, 5), (4, 5)]
>>> all(1 <= c <= 8 for coord in coords for c in coord)
True

Let's try two cases where there is a coordinate out of range:

>>> coords = [(3, 3), (4, 3), (5, 3), (6, 3), (3, 4), (0, 5),  (4, 4), (5, 4), (6, 4), (3, 5), (4, 5)]
>>> all(1 <= c <= 8 for coord in coords for c in coord)
False
>>> coords = [(3, 3), (4, 3), (5, 3), (6, 3), (4, 88), (3, 4), (4, 4), (5, 4), (6, 4), (3, 5), (4, 5)]
>>> all(1 <= c <= 8 for coord in coords for c in coord)
False