Python-二进制搜索 - 列表索引以外

发布于 2025-01-26 06:01:19 字数 1878 浏览 4 评论 0原文

我正在学习python programm(我完全是初学者),并且在我的二元搜索程序中有一个小问题。 这是我的代码:

import random

def binary_search():
    numbers = []
    for x in range(1, 100):
        y = random.randint(1, 100)
        numbers.append(y)
        numbers.sort()

    start_index = numbers[0]
    end_index = numbers[-1]
    mid_index = numbers[(end_index+start_index)//2]

    user_choice = int(input("Is it your number: " + str(int(numbers[mid_index])) + "? \n0 - your number is lower,\n1 - it's your number,\n2 - your number is higher: "))
    times = 0

    while user_choice != 1:
        times += 1
        if user_choice == 0:
            end_index = mid_index-1
            numbers = numbers[start_index:end_index]
        elif user_choice == 2:
            start_index = mid_index+1
            numbers = numbers[start_index:end_index]

        mid_index = (end_index+start_index)//2
        user_choice = int(input("Is it your number: " + str(int(numbers[mid_index])) + "? \n0 - your number is lower,\n1 - it's your number,\n2 - your number is higher: "))

    print("Oh, that was hard... but it took only " + str(times) + " times to guess your number!")

如果user_choice == 2的值,python给了我这个:

Traceback (most recent call last):
    File "C:\Users\Piotr\Desktop\IT\python\ćwiczenia\practice python\binary search v.2.py", line 38, in <module>
        binary_search()
    File "C:\Users\Piotr\Desktop\IT\python\ćwiczenia\practice python\binary search v.2.py", line 30, in binary_search
        user_choice = int(input("Is it your number: " + str(int(numbers[mid_index])) + "? \n0 - your number is lower,\n1 - it's your number,\n2 - your number is higher: "))
    IndexError: list index out of range

我不知道,为什么不工作,因为对于user_choice == 0或1的值效果很好。我看不到,哪里错了。

(也许我只是一个愚蠢的女孩,她不了解它的工作原理以及它应该如何工作。)

谢谢您的帮助。祝您有美好的一天,享受咖啡(或喝茶或喝任何您喝的咖啡):)

I'm learning Python programm (I'm totally beginner) and I have a little problem in my programm for binary search.
This is my code:

import random

def binary_search():
    numbers = []
    for x in range(1, 100):
        y = random.randint(1, 100)
        numbers.append(y)
        numbers.sort()

    start_index = numbers[0]
    end_index = numbers[-1]
    mid_index = numbers[(end_index+start_index)//2]

    user_choice = int(input("Is it your number: " + str(int(numbers[mid_index])) + "? \n0 - your number is lower,\n1 - it's your number,\n2 - your number is higher: "))
    times = 0

    while user_choice != 1:
        times += 1
        if user_choice == 0:
            end_index = mid_index-1
            numbers = numbers[start_index:end_index]
        elif user_choice == 2:
            start_index = mid_index+1
            numbers = numbers[start_index:end_index]

        mid_index = (end_index+start_index)//2
        user_choice = int(input("Is it your number: " + str(int(numbers[mid_index])) + "? \n0 - your number is lower,\n1 - it's your number,\n2 - your number is higher: "))

    print("Oh, that was hard... but it took only " + str(times) + " times to guess your number!")

If the value of user_choice == 2, Python give me this:

Traceback (most recent call last):
    File "C:\Users\Piotr\Desktop\IT\python\ćwiczenia\practice python\binary search v.2.py", line 38, in <module>
        binary_search()
    File "C:\Users\Piotr\Desktop\IT\python\ćwiczenia\practice python\binary search v.2.py", line 30, in binary_search
        user_choice = int(input("Is it your number: " + str(int(numbers[mid_index])) + "? \n0 - your number is lower,\n1 - it's your number,\n2 - your number is higher: "))
    IndexError: list index out of range

I have no idea, why doesn't work, because for the value of user_choice == 0 or 1 works well. I can't see, where is wrong.

(Maybe I'm just a stupid girl who doesn't understand how it works and how it should work well.)

Thank you for helping me. Have a nice day and enjoy your coffee (or tea or whatever you drink) :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

帅冕 2025-02-02 06:01:19

有几个问题:

  • 导致您遇到的错误的问题:您的代码切片nubset列表,但是当切片在右侧拍摄时,*_ index < /代码>变量现在指向错误的索引。以前在索引MID_INDEX + 1现在处于索引0,因此某些或全部这些变量是指超出范围的索引。解决方案是将您的列表切成薄片。更改索引变量可以完成所有需要的工作。


  • start_index =数字[0]没有分配 index ,而是该索引的值。它应该只是start_index = 0end_indexmid_index

  • 选择随机数可能会导致列表中的差距,并且可能是用户选择列表中未发生的值。该代码应仅创建一个列表,并允许用户选择所有可能的值,而无需任何随机性。

这不是问题,但是:

  • int(数字[mid_index]):不需要调用int,因为数字已经是int值的列表。

  • 也许验证user_choice是0、1或2,否则要打印一些消息。

  • 当用户说“少”时,也许会显示一条消息,但是价值不少,或“更大”,但没有更大的价值。

  • 有一些代码重复,例如input()mid_index的定义都是在第一次迭代之前和每次迭代结束时完成的。将该逻辑移到循环主体顶部,然后使用break退出循环。

这是修改的代码:

def binary_search():
    numbers = list(range(100))

    start_index = 0
    end_index = len(numbers) - 1

    times = 0
    while True:  # avoid code repetition, and break in middle of loop
        mid_index = (end_index+start_index)//2
    
        user_choice = int(input("Is this your number: " + str(numbers[mid_index]) + "?\n"
             + "0 - your number is lower,\n"
             + "1 - it's your number,\n"
             + "2 - your number is higher: "))
        times += 1
        if user_choice == 1:
            break
        if user_choice == 0 and mid_index > start_index:
            end_index = mid_index-1
        elif user_choice == 2 and mid_index < end_index:
            start_index = mid_index+1
        else:
            print("Invalid input")

    print("Oh, that was hard... but it took only " + str(times) 
        + " times to guess your number!")


binary_search()

There are several issues:

  • The issue that is causing the error you get: your code slices the numbers list, but when the slice is taken at the right side, the *_index variables point to the wrong indices now. What previously was at index mid_index + 1 now is at index 0, so some or all of those variables refer to indices that are out of range. The solution is to not slice your list. The changing index variables do all that is needed.

  • start_index = numbers[0] does not assign the index, but the value at that index. It should just be start_index = 0. The same mistake is made for end_index, and mid_index.

  • Picking random numbers may lead to gaps in your list, and it may be that the user chooses a value that does not occur in your list. The code should just create a list with every possible value that the user is allowed to choose, without any randomness.

Not a problem, but:

  • int(numbers[mid_index]): it is not needed to call int, as numbers is already a list of int values.

  • Maybe verify that user_choice is 0, 1 or 2, and otherwise print some message.

  • Maybe show a message when the user says "less" but there is no lesser value, or "greater" but there is no greater value.

  • There is some code duplication, like the input() and the definition of mid_index are done both before the first iteration, and at the end of each iteration. Move that logic at the top of the loop's body, and use break to exit the loop.

Here is the modified code:

def binary_search():
    numbers = list(range(100))

    start_index = 0
    end_index = len(numbers) - 1

    times = 0
    while True:  # avoid code repetition, and break in middle of loop
        mid_index = (end_index+start_index)//2
    
        user_choice = int(input("Is this your number: " + str(numbers[mid_index]) + "?\n"
             + "0 - your number is lower,\n"
             + "1 - it's your number,\n"
             + "2 - your number is higher: "))
        times += 1
        if user_choice == 1:
            break
        if user_choice == 0 and mid_index > start_index:
            end_index = mid_index-1
        elif user_choice == 2 and mid_index < end_index:
            start_index = mid_index+1
        else:
            print("Invalid input")

    print("Oh, that was hard... but it took only " + str(times) 
        + " times to guess your number!")


binary_search()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文