Answer the question
In order to leave comments, you need to log in
How to solve a problem using one formula and not using if, else, elif?
There is a task.
The user enters a number, conditionally from 1 to 100.
The program must guess the hidden number in the minimum number of steps, cycles, lines of code. After the program makes a guess, it can only get information greater than or less than the guessed number.
This is purely my personal interest, tell me only if you have nothing to do)
The world will not burn if this problem is not solved)
Answer the question
In order to leave comments, you need to log in
The algorithm is called "binary search" - google it.
And here "without using if"? We got the answer "more" OR "less" - then you need to take certain actions. It is possible to bypass directly the use of the conditional operator, but .. why?
Well, instead of if, you can use a list of functions (lambdas or regular ones).
x = 1
[
lambda: print('x < 0!'), #False = 0
lambda: print('x > 0!'), #True = 1
][x > 0]()
Binary search under such conditions is the input of an eight-bit number bit by bit, starting from the highest.
Binary search.
Can be implemented without if-s at all.
The bottom line is that you have a current segment. Find the middle, ask about it. You get the answer R = 0 or 1. Then you add half of the segment to the left border, multiplied by R, and subtract it from the right border, multiplied by 1-R. Thus, only one border will move. The question remains what to do with the exit from the loop. In the same place inside if is hidden.
You can either copy the code 7 times (2^7 > 100), or have an infinite loop that will compare the bounds and call one of the two functions in the 2-element array. One of the functions will print the answer and terminate the program with exit. The second one will do nothing.
After the program makes a guess, it can only get information greater than or less than the hidden number.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question