Here's the one-liner version of the square
function using lambda and list comprehension:
main.py103 chars2 lines
Explanation:
lambda num
: This defines an anonymous function with one parameter num
.1 << (num - 1)
: This is the same bitwise left-shift operation as before. It calculates 2^(num-1).if num in range(1, 65)
: This checks if the input num
is in the range from 1 to 64.else: valueerror("must be between 1 and 64")
: This raises a ValueError
with the specified message if the input is outside the range.Please note that using a lambda function and list comprehension is not always the best approach, especially for more complex functions. It's important to prioritize readability of code when choosing between different coding styles.
gistlibby LogSnag