N
N
nihi1ist2021-09-16 12:08:08
Python
nihi1ist, 2021-09-16 12:08:08

Task in Python. How to find a number?

I solve the problem. You need to write a code with which you can calculate a number (from 1 to 100) by answering questions (1 - equal, 2 - more, 3 - less.). In this case, the number must be guessed within 7 attempts. Logically, I can imagine how to do this, but how to implement it in code does not reach me.
The initial number is 50, the step is 24. How to track that if at first it was more, the number decreased by 24 and became less. Should I cut the step in half?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
antares4045, 2021-09-16
@nihi1ist

Your task is called binary search

def binsearch(min, max, check):
    support = (min + max) // 2
    result = check(support)
    if result == 'меньше':
        return binsearch(support+1, max, check)
    if result == 'больше':
        return binsearch(min, support-1, check)
    return support

def guess(num):
    print('загадано', num)
    def check(req):
        result = 'равно' if req == num else 'меньше' if req < num else 'больше'
        print(f'это {req}?', '-', 'Да' if result=='равно' else f'Нет, твоё число {result}')
        return result
    return check


binsearch(0, 100, guess(10))
print('='*30)
binsearch(0, 100, guess(27))
print('='*30)
binsearch(0, 100, guess(50))
print('='*30)
binsearch(0, 100, guess(100))

guess 10
is 50? - No, your number is more than
24? - No, your number is more than
11? - No, your number is more than
5? - No, your number
is less than 8? - No, your number
is less than 9? - No, your number
is less than 10? - Yes
=============================
27
is 50? - No, your number is more than
24? - No, your number
is less than 37? - No, your number is more than
30? - No, your number is more than
27? - Yes
=============================
50
is 50? - Yes
=============================
100
is 50? - No, your number
is less than 75? - No, your number is less
is it 88? - No, your number
is less than 94? - No, your number
is less than 97? - No, your number
is less than 99? - No, your number
is less than 100? - Yes

L
lirostin, 2021-09-16
@lirostin

nihi1ist I advise you to solve easy problems on leetcode to consolidate the material. Here is a section with binary search tasks: https://leetcode.com/tag/binary-search/ ; )
You understood from the example of the solution how to implement it? You can write a solution to the problem:
Given an array arr and a number K. You must output True if the number is in the array or output False if it is not.
Examples:
Input:
K = 6
arr = [1,2,3,4,6]
Output: True
Input:
K = 2
arr = [1,3,4,5,6]
Output: False

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question