Python 3-liner with test cases and TIO link.
Apart from some type conversions, itertools.compress does the job.
importitertoolsfilterlist=lambdavalue,length:map(int,bin(value)[2:].zfill(length))grille=lambdastring,grille:''.join(itertools.compress(string,filterlist(grille,len(string))))cases=[('abcdef',5),('0abc',2),('abcde',32),('abcd',1)]forcaseincases:print(f'grille{case} has filter {list(filterlist(case[1],len(case[0])))} and outcome: {grille(*case)}')
Python 3-liner with test cases and TIO link.
Apart from some type conversions, itertools.compress does the job.
Try it online!