Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Interleaving tuple with predicates

I need to define a function interleaved_tuple_picky that takes three arguments, tuple_a, tuple_b and predicate and return a tuple of values either from tuple_a or tuple_b. For all values x from tuple_a, we will add x to the final tuple if predicate(x) is True, else we will add the corresponding value from tuple_b. For example interleaved_tuple_picky(a, b, is_odd) will return (1, 11, 3, 15, 5)
interleaved_tuple_picky(c, b, is_odd) will return (9, 11, 13, 15, 17)

Currently, I have this, not too sure how to move on from this?

def interleaved_tuple(tuple_a,tuple_b):
    return (sum(zip(tuple_a, tuple_b), ()))

def interleaved_tuple_picky(tuple_a, tuple_b, predicate):
    tuple_x = interleaved_tuple(tuple_a,tuple_b)
    for i in tuple_x:
        if predicate(i)==True:
            tuple_y = ()
            tuple_y =+ (i,)
        
        return tuple_y

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

  • You want to go through all pairs in the tuples tuple_a and tuple_b, so you need to iterate over zip(tuple_a, tuple_b), so your generator expression becomes (_____ for x, y in zip(tuple_a, tuple_b))
  • You want to select x if predicate(x), else y. So your expression is: (x if predicate(x) else y for x, y in zip(tuple_a, tuple_b))
  • You want to convert this to a tuple before returning: return tuple(x if predicate(x) else y for x, y in zip(tuple_a, tuple_b))

So you have:

def interleaved_tuple_picky(tuple_a, tuple_b, predicate):
    return tuple(x if predicate(x) else y for x, y in zip(tuple_a, tuple_b))

tuple_a = (1, 2, 3, 4, 5)
tuple_b = (10, 11, 12, 13, 14)

interleaved_tuple_picky(tuple_a, tuple_b, lambda x: x % 2)
# (1, 11, 3, 13, 5)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading