Reethika
Reethika

Reputation: 21

Lambda function for replacing characters in the string

Below is the Python code to replace characters. Can some explain the lambda part? Initially, X is taking "p" and checking if its a1 or a2. where is the swap happening?


def replaceUsingMapAndLambda(sent, a1, a2):
    # We create a lambda that only works if we input a1 or a2 and swaps them.
    newSent = map(lambda x: x if(x != a1 and x != a2) else a1 if x == a2 else a2, sent)
    print(newSent)
    return ''.join(newSent)


print(replaceUsingMapAndLambda("puporials toinp", "p", "t"))

output:

$python main.py
['t', 'u', 't', 'o', 'r', 'i', 'a', 'l', 's', ' ', 'p', 'o', 'i', 'n', 't']
tutorials point 

Thanks, Reethika

Upvotes: 2

Views: 4569

Answers (3)

MercyDude
MercyDude

Reputation: 914

It takes the String (or List) which in this case is : "puporials toinp"

And then it Iterates through each character/item in the string/list and checks the following: (I'll break the lambda code for you)

lambda x: x if(x != a1 and x != a2) else a1 if x == a2 else a2

1) If the char/item is not equal to a1 and not equal to a2 it map it to the same character it checked.

Which is this piece of code: x if(x != a1 and x != a2)

Else

2) it maps the value of a1 if the character equals a2 and if not it maps a2.

Which is this piece of code: else a1 if x == a2 else a2

Then the newSent is a map object which contains the chars (with the logic explained above), and converts it back to a String with the ''.join(newSent) command.

Upvotes: 0

Thijs van Ede
Thijs van Ede

Reputation: 917

To avoid any confusion, lets first extract the lambda function and see what it does. The lambda function is defined as

lambda x: x if(x != a1 and x != a2) else a1 if x == a2 else a2

A lambda statement avoids the definition of creating a named function, however any lambda function can still be defined as a normal function. This specific lambda function uses a ternary operator. This can be expanded to a regular if-else statement. This would lead to an equivalent regular function like this

def func(x, a1, a2):
    if x != a1 and x != a2:
        return x
    elif x == a2:
        return a1
    else:
        return a2

Upvotes: 1

Corentin Limier
Corentin Limier

Reputation: 5006

This is the same as :

def replaceUsingMapAndLambda(sent, a1, a2):
    # We create a lambda that only works if we input a1 or a2 and swaps them.
    newSent = []
    for x in sent:
        if x != a1 and x != a2:
            newSent.append(x)
        elif x == a2:
            newSent.append(a1)
        else:
            newSent.append(a2) 

    print(newSent)
    return ''.join(newSent)

Lambda is a keyword to create an anonymous function and map applies this anonymous function to every element of the list and returns result.

Upvotes: 1

Related Questions