Discovering an elusive number using the fewest attempts possible

I'm currently working on a Python script to efficiently find an unknown number with the fewest attempts possible.

The only information I have about the mystery number is that it is less than 10000.

Each time I input the wrong guess, I receive an "error" message. But when I correctly identify the number, I get a "success" message.

For the sake of this example, let's say the number we are trying to find is 124.

How would you go about solving this challenge using Python?

I appreciate any guidance as I am finding this problem quite challenging :(

Answer №1

When the only information you have is that a number is less than 10000, you will need to check all numbers between 1 and 9999 (inclusive). The binary search algorithm suggested in the comments may not be helpful in this case as a miss does not provide any indication of whether the target number is higher or lower.

for i in range(1, 10000):
    if i == number_you_are_looking_for:
        print("found it")
        break

Answer №2

One efficient method to find a number is binary search, solving it in O(log n) time complexity.

def binary_search(n, min_value, max_value):
    attempts = 0
    is_found = False

    if max_value < min_value:
        print("The maximum value must be greater than the minimum value")
    elif n < min_value or n > max_value:
        print("The number should be within the range of min_value and max_value")
    else:
        while min_value < max_value and not is_found:
            attempts += 1

            mid_value = (min_value + max_value)//2

            if mid_value == n:
                is_found = True
            else:
                if n < mid_value:
                    max_value = mid_value - 1
                else:
                    min_value = mid_value + 1

            print([(min_value, max_value), (mid_value, n), attempts])

        print("The number is:", str(n))
        print("Attempts:", str(attempts))

Examples:

binary_search(7, 0, 10)
>> The number is: 7
>> Attempts: 2

binary_search(667, 0, 1000)
>> The number is: 667
>> Attempts: 8

binary_search(2**19, 2**18, 2**20)
>> The number is: 524288
>> Attempts: 19

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Selenium tips: Tricks to get past Cloudflare's bot protection

For educational purposes, I am looking to extract information from a website. However, I am facing obstacles due to the protection measures in place. Every time I try to send requests, I encounter the familiar "Checking-your-browser" page followed by con ...

What could be causing this error to appear when I try to run the makemigrations command?

from django.db import models # Defining the Products model class Products(models.Model): title = models.TextField() description = models.TextField() price = models.TextField() An issue has arisen and I am unsure why. Here is the error messag ...

What is the reason behind the lack of granularity in the ruby `require` statement?

Unique example for better understanding In my script file, labeled as c.py, I have defined two classes: Elephant and Giraffe. When working with Python, to utilize the Elephant class from the c.py file, an import statement is used: import c print(Elepha ...

Python script for extracting OTP from Twilio SMS

Currently, I am diving into a web automation project using the selenium python-pytest framework. The challenge I'm facing involves the generation of an OTP after entering my phone number, which then needs to be retrieved and inputted into a text box o ...

What is the method for sorting a Python list both numerically in descending order and alphabetically in ascending order simultaneously?

My goal is to arrange a list that contains tuples with a word and a number. my_list = [('hello',25), ('hell',4), ('bell',4)] I am looking for a way to sort this list (maybe using lambda) in order to achieve the following: [ ...

Steps for sending a message to a server using WebSockets

My goal is to establish communication with a Server in order to receive responses. I attempted to utilize the official websocket APIs provided by the website, but I found them confusing or not functioning as desired. Therefore, I am exploring the option o ...

When should you invoke django.setup()?

Can someone help me understand the purpose of django.setup()? Should I include it in my settings file? I encountered an issue when calling apps.get_models() and received the following error message: django.core.exceptions.AppRegistryNotReady: Models aren ...

Having trouble accessing dynamically generated elements using Selenium

I've been attempting to change the router's SSIDs using a Selenium script, but I'm encountering difficulty accessing any JS elements generated by the router page. I've tried various Expected Conditions and methods without success. Here ...

Module 'chalk' could not be located

As part of a Trainee DevOps interview exercise, I am tasked with building and deploying a web app using Docker-Compose with Django backend and React frontend. The code has been provided to me, and the focus is on completing the build and deploy process. A ...

Utilizing Selenium to Override SSL Certification in Internet Explorer Using Python

After extensive research on this issue, I have yet to come across any viable solutions. My current project involves writing a script using Selenium to automate logging into a specific website. However, my efforts are being hindered by a certificate warning ...

Leveraging Python's Selenium module for extracting time information

In my code snippet below, I am attempting to extract the utime of an element. Despite confirming that I am targeting the correct area and that the utime attribute is present, the output always shows as None. I have double-checked the formatting of the data ...

Python script to extract data from a JSON file

Struggling to read data from a JSON file and display the values? Having trouble figuring out how to access all the values from the first dictionary in the list? Here's what you want to print: website: https://www.amazon.com/Apple-iPhone-GSM-Unlocke ...

What is the best way to utilize the data in a file as a parameter?

I recently installed AutoKey on my computer with the intention of being able to run python scripts using keyboard shortcuts. Specifically, I wanted to create a script that would simulate pressing the "d" key followed by the "s" key in a loop, with the abil ...

Display text by representing it as Unicode values

Is there a way to display a string as a series of unicode codes in Python? Input: "こんにちは" (in Japanese). Output: "\u3053\u3093\u306b\u307b\u308c\u307e\u3057\uf501" ...

What is the best way to modify my if statement to avoid output duplication in my outfile?

When testing for a key, I either do a json.dump if it's present or add it if it's not. Additionally, I check for two other keys and add them if they are absent. I have nested these secondary tests. The issue with the current code is that if the ...

What is the Unicode representation for the character "你"?

I recently learned that the Unicode for 你 (meaning you) is \x4F\x60. Is there a way to retrieve it using my Python command console? >>> print("你") 你 >>> print(("你").encode("gbk")) b'\xc4\xe3' >&g ...

Is it possible to save and utilize cookies in a program without relying on the selenium driver.add_cookie

In the midst of a project, I find myself faced with the task of extracting URLs for all products on a given page and utilizing Scrapy to sift through each URL for product data. The challenge arises when a pop-up emerges 3-5 seconds after loading every URL, ...

Instructions on how to configure an extension in geckodriver using Selenium with Python

Recently, I attempted to load the Zenmate VPN extension in the Firefox driver using the following code. Despite successfully opening the driver, the extension failed to load. from selenium import webdriver profile = webdriver.FirefoxProfile() profile.add_ ...

Creating a new groupby object in Pandas python with no existing groups initialized

I am working with a substantial dataframe and need to group it by three specific columns before applying a function to each group. One challenge I am facing is that there are certain groups and keys missing from the dataframe which I am also interested i ...

Ways to stretch the non-logarithmic x-axis on the ln(x) graph

I am attempting to calculate various functions, such as ln(x), on an interval from 1 to 10. However, I want to plot these functions on a specific range of x values spanning from x[-1, 10]. I am facing difficulty in adjusting the ticks as desired, where the ...