Home > Software design >  Lambda function to flip bits(1 to 0 and 0 to 1) in binary
Lambda function to flip bits(1 to 0 and 0 to 1) in binary

Time:09-21

I have been solving hackerrank problems, and currently in a problem where I'm supposed to convert the number to binary, reverse each digit.

Let's say there's an integer n, I convert it to binary using:

g = '{0:032b}'.format(n)

Now I have reversed 0s and 1s using the normal for loop, but, I would like to do the same using lambda function and/or the one-line for loop.

I have tried doing so like:

f = [lambda x: x = '1' if x == '0' else x = '1']
res = [f(x) for x in g]    

and

res = [x = '1' for x in n if x == '0' else x = '0'] 

But I don't seem to get the syntax right. Also, if there's other better and shorter ways, kindly do enlighten me.
Any help would be appreciated!

CodePudding user response:

You can do like this,

In [1]: l = ["0", "1", "0", "0", "1"]
In [2]: f = lambda x: "1" if x == "0" else "0"
In [3]: [f(i) for i in l]
Out[3]: ['1', '0', '1', '1', '0']

Assigning lambda is a bad practice you could use a function itself.

In [4]: def f(x):
     ...:     if x == "0":
     ...:         return "1"
     ...:     else:
     ...:         return "0"

In [5]: [f(i) for i in l]
Out[5]: ['1', '0', '1', '1', '0']
  • Related