+ 1
How to convert decimal into binary using lambdas ?
I am trying to print the binary values of decimal numbers by using python inbulit lambdas input : 32 output : 0010 0000 My attempt : https://code.sololearn.com/c4vqA840S8Da/?ref=app
5 odpowiedzi
+ 10
Jan Markus , your solution is unbeatable short and clear. here is an solution with bin() function:
for integer 5 it will give:
0b101
so it contains a prefix "0b" that this number is a binary number. when converting these kind of numbers back to integer, it can be done with:
int(0b101) => 5
If you don't need the prefix, it can be done like this, and then adjusted to the desired lenth:
print(bin(a)[2:].zfill(8))
which results in : 00000101
+ 4
how to do this with a lambda expression:
to_bin = lambda num: to_bin(num//2) + str(num%2) if num else ""
+ 1
I find no reason to use a lambda here:
a, b = int(input()), 0
while a > 0:
b.insert(0, a % 2)
a // 2
print(b)
But if you really want it in your code, you can do it like this:
(lambda x: x % 2) (a)
I only use them with map/filter and functions.
+ 1
Jan Markus you are Genius sir! 🎉🎉 😉
you made my day!
can we do this..
can't we convert that function(i shown in my attempt) into lambda
expression??🤔
not a problem if "no" because your code is impressing.. 🎊
I am fell in love with "f-strings" ❤️
+ 1
Jan Markus I didn't know thay f strings could do this job so easily. Thanks.