Reputation: 29159
The following code gets correct answer because list()
is called before assigning to b
. max(b)
may get wrong value if removing list
.
a = map(lambda x: (x[0]*10 + x[1], x[2]*10 + x[3]), aLongList)
b = list(filter(lambda x: x[0] < 24 and x[1] < 60, a)) # convert to a list
if not any(b):
#.... omitted
max(b)
Is it a way to get the right result without creating a list (in case the list is huge)?
Test:
The following code
def perm(A):
for i,x in enumerate(A):
for j,y in enumerate(A):
if i == j: continue
for k,z in enumerate(A):
if i == k or j == k: continue
for l,a in enumerate(A):
if l == i or l == j or l == k: continue
yield [A[i], A[j], A[k], A[l]]
a = map(lambda x: (x[0]*10 + x[1], x[2]*10 + x[3]), perm([1,9,6,0]))
b = (filter(lambda x: x[0] < 24 and x[1] < 60, a)) # Removed list, so b is a filter obj instead of list
if not any(b):
pass
max(b)
returns (16, 9)
instead of (19, 6)
.
Upvotes: 0
Views: 150
Reputation: 29742
Use itertools.tee
.
Return n independent iterators from a single iterable.
from itertools import tee
b1, b2 = tee(filter(lambda x: x[0] < 24 and x[1] < 60, a), 2)
if not any(b1):
pass
max(b2)
Output:
(19, 6)
Upvotes: 1