Itertools - Advanced Filtering using Lambda

47 Views Asked by At

I have written a code using itertools library to find all the possible combination of 6 elements within a set of elements by applying several filters.

I have also managed to save the results to a txt file so I can load it into a SQL table easily.

However I have realised I can add some further filtering alongside the one I have already applied but I am struggling to understand how those have to be coded.

My current code is the following:

import numpy as np

M = np.array(np.transpose(np.loadtxt('C:\\py\\Numeri90.csv')))

n=6

from itertools import combinations

combos = filter(lambda e:   (np.min(e[0]) <= 41) and 
                            ((e[2]-e[0]) > 4) and
                            (np.sum(e) <= 398) and 
                            ((e[0]+e[1]+e[2]+e[3]+e[4]) <= 311) and 
                            ((e[0]+e[1]+e[2]+e[3]+e[4]) > 93) and                                 
                            ((e[0]+e[1]+e[2]+e[3]) > 50) and 
                            ((e[0]+e[1]+e[2]) <= 157) and ((e[0]+e[1]+e[3]) <= 164) and                                 
                            ((e[0]+e[1]) <= 93) and 
                            ((e[0]+e[1]) > 6) and 
                            (np.std(e) <= 33.15) and 
                            (np.std(e) > 11.99) and
                            , combinations(M, n))  

file = open ("C:\\py\\Colonne.txt","w")

for row in combos:
    print(row)
    res = str(','.join(map(str,row)))
    file.write(res)
    file.write('\n')
file.close()

What I would like to add now is two further condition:

  1. The first one will discard the combos where all elements are odd numbers. To do so I have tried to add a condition using the code below but do not work. What I am trying to achieve is that the combination in the list can't have all pair or all odd numbers

    ((e() % 2 != 0) > =1)

Can anyone help me how to better understand and implement that filter/condition using lambda within itertools?

  1. The second goal I am trying to achieve would be to exclude, from all the possible combinations given the above filtering, all the combination (list) I have stored in a separate txt file. Those combinations, despite could be the possible output of itertools, are by definition impossible hence I'd like to filter to exclude them. on this I have no idea how to proceed hence any help/hint will be appreciated
0

There are 0 best solutions below