Search code examples
pythonfunctional-programming

How do I use lambda to replace for loop and still maintained functional programming?


this is the original code

def cage_cats(S): 
    maxtemp = 0
    temp = list(set(S))
    for i in range(len(temp)-1):
        for j in range(len(S)-1):
            if temp[i] == S[j]:
                if S[j] == S[j+1]:
                    break
                else:
                    maxtemp = max(S[j], maxtemp)

    return maxtemp 

And below is the code I'm attempting to make to replicate the code above with different method

def cage_cats(S):
    temp = list(set(S))
    maxtemp = max(
        list(
            map(
                lambda i : (
                    lambda j : (
                        S[j] if temp[i] == S[j] and S[j] == S[j+1] else "None"
                    ),range(len(S)-1)
                ),range(len(temp)-1)
            )
        )
    , 0)

Where do I go wrong in my code? I'm kinda lost on what to do. Is there a method I can use to make the result the same as the original code but still maintain the functional programming part of it?

Edit :

This code is to find the maximum element that is not next to each other.

The length of input will always be even and also every number in the list will only appear 2 times.

For example:

[1, 1, 2, 2, 5, 3, 3, 5] the answer would be 5

[1, 2, 2, 3, 1, 5, 5, 3] the answer would be 3

[1, 1, 2, 2, 3, 3] it would be 0 ( default value )


Solution

  • Here's a solution using only max and some list comprehension to replace the 2 for loops by only 1.

    It works by comparing all the elements in your list with the one before and after and checking if its different to both or no

    S = [1, 2, 2, 3, 1, 5, 5, 3]
    S = ["", *S, ""] # pad with values that you're sure aren't in your list
    filtered_S = [b for a, b, c in zip(S, S[1:], S[2:]) if a != b != c]
    sol = max(filtered_S, default=0)
    # sol = 3
    

    Edit :

    If you want to completely replace for loops, you can also use filter and map to build filtered_S (filter does the filtering using the zipped list, and map takes back the element that interests us)

    filtered_S = map(
        lambda t: t[1], 
        filter(
            lambda t: t[0] != t[1] != t[2], zip(S, S[1:], S[2:])
        )
    )