Reputation: 3591
I have a 3 lists :
a = [10, 9, 8, 7, 6]
b = [8, 7, 6, 5, 4, 3]
c = [6, 5, 4, 3, 2]
I need to get all the permutations obtained with itertools.product()
, BUT only if the values are decreasing:
[10, 8, 6] # is good
[6, 8, 4] # is not good, since 8 > 6
Is there a simple way to do it or should I go with list comprehension and conditions ?
Upvotes: 1
Views: 67
Reputation: 96
You can refer following code which does not have list comprehensions:
from itertools import product
a = [10, 9, 8, 7, 6]
b = [8, 7, 6, 5, 4, 3]
c = [6, 5, 4, 3, 2]
for result in product(a,b,c):
if sorted(result, reverse = True) == list(result):
print result
Upvotes: 2
Reputation: 41218
You could do this with a list comprehension by looping over theitertools.product
iterator and extracting only those returned items that are sorted in reverse:
[item for item in product(a,b,c) if sorted(item, reverse = True) == list(item)]
Example:
from itertools import product
a = [10,9,8,7,6]
b = [8, 7, 6, 5, 4, 3]
c = [6, 5, 4, 3, 2]
[item for item in product(a,b,c) if sorted(item, reverse = True) == list(item)]
# [(10, 8, 6), (10, 8, 5), (10, 8, 4), (10, 8, 3), (10, 8, 2) ...continues
Upvotes: 3
Reputation: 122
If you don't want to use list comprehensions for some reason:
def decreasing(l):
return all(a >= b for a, b in zip(l[:-1], l[1:]))
filter(decreasing, product(a, b, c))
Upvotes: 0
Reputation: 5349
This is a simple one line solution
>>> mylist = [10, 9, 8, 7, 6]
>>> all(earlier >= later for earlier, later in zip(mylist, mylist[1:]))
True
>>> mylist = [10, 9, 7, 8, 6]
>>> all(earlier >= later for earlier, later in zip(mylist, mylist[1:]))
False
I found this here:
Determine if a list is in descending order
Upvotes: 0