T
T
Taros2021-08-09 12:31:53
Python
Taros, 2021-08-09 12:31:53

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

6 answer(s)
S
Sergey Sokolov, 2021-08-09
@sergiks

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?

V
Vindicar, 2021-08-09
@Vindicar

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]()

Then it’s easy to build a decision tree from such blocks using the dichotomy method.

A
Armenian Radio, 2021-08-09
@gbg

Binary search under such conditions is the input of an eight-bit number bit by bit, starting from the highest.

G
Griboks, 2021-08-09
@Griboks

x=input() 
while x!=random() :pass

W
Wataru, 2021-08-09
@wataru

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.

A
Alexandroppolus, 2021-08-09
@Alexandroppolus

After the program makes a guess, it can only get information greater than or less than the hidden number.

and if the guess turned out to be equal to the guessed number, then what?
why I asked: if infa about equality is allowed, you can guess in 6 attempts, and not in 7.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question