Just for fun, I am trying to compress a programming problem into one line. I know this is typically a bad practice, but it is a fun challenge that I am asking for your help on.
I have a piece of code which declares the variables and in the second line which loops over a list created in the first line, until a number is not found anymore. Finally it returns that value.
The programming question is as follows. Given a sentence, convert each character to it's ascii representation. Then convert that ascii value to binary (filling the remaining spaces with 0 if the binary number is less than 8 digits), and combine the numbers into one string. Find the largest base 10 integer which when converted to binary is in the string.
You can see my code below
def largest_binary_number(sentence: str):
binary_string, n = ''.join(['0'*(10-bin(ord(char))) bin(ord(char))[2:] for char in sentence]),0
while bin(n)[2:] in binary_string: n =1
return n-1
It would also be nice if I could combine the return statement and loop into one line as well.
CodePudding user response:
The function can be defined the function this way, thanks to @treuss' observation:
def largest_binary_number(sentence: str):
return int(''.join([bin(ord(char))[2:].zfill(8) for char in sentence]), 2)
But suppose that the problem was to "find the smallest base 10 integer larger than 1000 whose binary representation is in the string." Then we have something like this:
def find(sentence: str):
return list(iter(lambda: globals().__setitem__('_c', globals().get('_c', 1000-1) 1) or bin(globals().get('_c'))[2:] in ''.join([bin(ord(c))[2:].zfill(8) for c in sentence]), True)) is type or globals().get('_c')
Let's break this down into four parts:
globals().__setitem__('_c', globals().get('_c', 1000-1) 1)
- initialize and increment a counter... or bin(globals().get('_c'))[2:] in ''.join([bin(ord(c))[2:].zfill(8) for c in sentence])
- check if the binary representation of the counter is in the binary representation of the sentencelist(iter(lambda: ..., True))
- inline while loop using black magic... is type or globals().get('_c')
- get the final value of the counter, which satisfies our condition
Part 1: globals().__setitem__('_c', globals().get('_c', 1000-1) 1)
Since we are confined to do everything in one line, we don't have the luxury of defining variables. This is where globals
comes in: we can store and use arbitrary variables as dictionary entries using the __setitem__
and get
methods. Here we name our counter variable _c
, calling get
to initialize and fetch the value, then immediately increment it by one and save the value with __setitem__
. Now we have a counter variable.
Part 2: ... or bin(globals().get('_c'))[2:] in ''.join([bin(ord(c))[2:].zfill(8) for c in sentence])
bin(globals().get('_c'))[2:]
converts the counter to binary and removes the 0b
prefix. ''.join([bin(ord(c))[2:].zfill(8) for c in sentence])
, as before, converts the input sentence to binary. We use in
to check if the binary counter is a substring of the binary sentence. Because the __setitem__
call from part 1 returns None
, we use or
here to ignore that and execute this part.
Part 3: list(iter(lambda: ..., True))
This is the bread and butter, allowing us to perform inline iteration. iter is usually passed an iterable to create and iterator, but it actually has a second form that takes two arguments: a callable and a sentinel. When iterating over an iterator created using this two-argument form, the callable is successively called until it returns the sentinel value (beware infinite loops!). So we define a lambda function that returns True
when the condition is satisfied, and set the sentinel to True
. Finally we use the list
constructor to begin iterating.
Part 4: ... is type or globals().get('_c')
Once the list
constructor finishes iterating, we need to fetch and return the final value of the counter. We follow list(...)
with is type
to make an expression that always evaluates to False
, then chain it with or globals().get('_c')
at the end of this one-liner to return the counter. Et voilà!
Note: In hindsight, maybe the walrus :=
could be used to make the counter, instead of having to call globals()
every time. However, replacing globals
with locals
doesn't work for some reason.
Note 2: Using these techniques, we can make one-liners that satisfy various conditions.
CodePudding user response:
You can use ;
syntax, but I am not sure if that is going to be a good enough solution in this situation, because you are trying this as a challenge. The syntax for it goes like this <statement1>;<statement2>
.
So your code would look something like this:
def largest_binary_number(sentence: str):
binary_string, n = ''.join(['0'*(10-bin(ord(char))) bin(ord(char))[2:] for char in sentence]),0; while bin(n)[2:] in binary_string: n =1; return n-1