gpt4 book ai didi

python - 返回列表中给定数字之前的数字

转载 作者:太空宇宙 更新时间:2023-11-03 14:46:38 24 4
gpt4 key购买 nike

我正在尝试编写一个二分搜索,它将在有序列表中的给定数字之前产生最大的数字。

y = int(input("Enter a number:"))
numblist = [5, 8, 9, 10, 18, 20, 25, 28, 30, 35]

lowerval = numblist[0]
higherval = numblist[9]
number = 0

mid = (higherval + lowerval)//2

for y in numblist:
number += 1
if mid == y:
print(number)
break

if mid < y:
lowerval = mid
else:
higherval = mid
mid = (higherval + lowerval)//2

例如,如果我输入20,返回的数字应该是18。老实说,我不知道如何调用正确的位置。我对 python 非常陌生,所以任何帮助将不胜感激。

最佳答案

以下代码片段将完成您想要的操作,尽管方式相对笨拙(但更容易理解):

# Ask the user for an input
y = int(input("Enter a number: "))
# List of numbers to be searched
numblist = [5, 8, 9, 10, 18, 20, 25, 28, 30, 35]

# Set the lower bound of the search
lowerval = numblist[0]
# Set the upper bound of the search
higherval = numblist[-1]


# Search Algorithm
while True:
mid = (lowerval + higherval) // 2
if mid == y:
# Here, I am assuming that you will only test against a list with only unique values.
# It first indexes the value that was found, then subtracts one from it to obtain the value prior to the found value.
print(numblist[numblist.index(y) - 1])
# Then it exits the while loop.
break
if mid < y:
lowerval = mid
if mid > y:
higherval = mid

希望这有帮助!

关于python - 返回列表中给定数字之前的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46187613/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com