Python One-Liners: Higher or Lower
MarcusWeinberger (595)

Here is an example of the game "higher or lower" written in a single line. I've used a variety of tricks to make this work in a single line such as:

  • globals().setattr to let me set variables inside a lambda function
  • (globals().setattr("guess",x) or globals ()["guess"]) to use the := operator in python 3.7, the := operator only being introduced in python 3.8 which has yet to upgrade to
  • for i in iter(int, 1) instead of a while loop which would require more than one line

And some others. If you'd like, share some of your other one-line programs because I'm interested in them at the moment.

You are viewing a single comment. View All
mwilki7 (1113)

The added constraint of making it a one liner is actually pretty hard lol
I feel like I cheated a bit with the while loop

console.log((c=>{while((g=prompt("guess"))!=c)console.log(g<c?"higher":"lower");return "you won"})(0|Math.random()*0xFF));
( parameter => function body) (parameter passed to the function)
(0|Math.random()*0xFF): random number between 0 and 255
The 0| part truncates it so it's an integer

console.log (
    ( parameter) => {
        while (get input)
            print higher or lower based on input
        return "you won"