Programming-Idioms

History of Idiom 43 > diff from v49 to v50

Edit summary for version 50 :
[Python] Evaluate the matrix lazily to avoid one full outer loop

Version 49

2020-01-09, 17:07:28

Version 50

2020-01-09, 17:11:45

Idiom #43 Break outer loop

Look for a negative value v in 2D integer matrix m. Print it and stop searching.

Illustration

Idiom #43 Break outer loop

Look for a negative value v in 2D integer matrix m. Print it and stop searching.

Illustration
Imports
from itertools import chain
Imports
from itertools import chain
Code
matrix = [[1,2,3],[4,-5,6],[7,8,9]]
try:
	print(next(i for i in chain(*matrix) if i < 0))
except StopIteration:
	pass
Code
matrix = [[1,2,3],[4,-5,6],[7,8,9]]
try:
    print(next(i for i in chain.from_iterable(matrix) if i < 0))
except StopIteration:
    pass
Comments bubble
We make a generator that will return negative values from a list (and use chain(*matrix) to flatten the 2d list into a 1d list) and only take one value from it with the next function.

This will raise StopIteration if it doesn't find the value so we need to account for it.
Comments bubble
We make a generator that will return negative values from a list (and use chain.from_iterable(matrix) to lazily extract the values) and only take one value from it with the next function. The generator will not continue until we call next again.

This will raise StopIteration if it doesn't find the value so we need to account for it.
Demo URL
https://ideone.com/0Bo95p
Demo URL
https://ideone.com/0Bo95p