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
>Solution :
- You want to go through all pairs in the tuples
tuple_aandtuple_b, so you need to iterate overzip(tuple_a, tuple_b), so your generator expression becomes(_____ for x, y in zip(tuple_a, tuple_b)) - You want to select
xifpredicate(x), elsey. 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)