我是python的初学者,我正在执行二进制搜索任务,我正在尝试一种与普通代码不同的代码。我的问题是我不能返回一个新的二进制列表。第一次函数按预期工作,但第二次函数没有返回新列表。
我的代码:
import random, math
user_choice=random.randint(0,100)
print (user_choice)
max=100
number_elements=50
number_list=random.sample(range(max), number_elements)
sort_list=sorted(number_list)
print (sort_list)
count=0
limit=int(math.sqrt(number_elements))
# divide by 2 the length of the number_list
def divide_list(sort_list):
global count,number_elements
number_elements=int(number_elements//2)
count += 1
half=len(sort_list)//2
if user_choice <= sort_list[number_elements] :
sort_list=sort_list[:half]
print(sort_list)
else :
sort_list=sort_list[half:]
print(sort_list)
return sort_list
while len(sort_list)==0 or count <=limit:
max /= 2
divide_list(sort_list)
输出:
99
[5, 6, 8, 9, 14, 15, 17, 18, 19, 22, 23, 24, 26, 27, 28, 34, 35, 36, 38, 39, 40, 41, 44, 46, 47, 48, 50, 51, 53, 54, 55, 56, 57, 58, 61, 63, 64, 65, 67, 68, 69, 75, 76, 80, 81, 86, 90, 96, 97, 99],
[48, 50, 51, 53, 54, 55, 56, 57, 58, 61, 63, 64, 65, 67, 68, 69, 75, 76, 80, 81, 86, 90, 96, 97, 99]
[48, 50, 51, 53, 54, 55, 56, 57, 58, 61, 63, 64, 65, 67, 68, 69, 75, 76, 80, 81, 86, 90, 96, 97, 99]
[48, 50, 51, 53, 54, 55, 56, 57, 58, 61, 63, 64, 65, 67, 68, 69, 75, 76, 80, 81, 86, 90, 96, 97, 99]
[48, 50, 51, 53, 54, 55, 56, 57, 58, 61, 63, 64, 65, 67, 68, 69, 75, 76, 80, 81, 86, 90, 96, 97, 99]
[48, 50, 51, 53, 54, 55, 56, 57, 58, 61, 63, 64, 65, 67, 68, 69, 75, 76, 80, 81, 86, 90, 96, 97, 99]
[48, 50, 51, 53, 54, 55, 56, 57, 58, 61, 63, 64, 65, 67, 68, 69, 75, 76, 80, 81, 86, 90, 96, 97, 99]
[48, 50, 51, 53, 54, 55, 56, 57, 58, 61, 63, 64, 65, 67, 68, 69, 75, 76, 80, 81, 86, 90, 96, 97, 99]
[48, 50, 51, 53, 54, 55, 56, 57, 58, 61, 63, 64, 65, 67, 68, 69, 75, 76, 80, 81, 86, 90, 96, 97, 99]
谢谢你的帮助。
您的函数正在返回列表,但您没有存储/更新它。
解决方案:
将线路divide_list(sort_list)
更改为sort_list = divide_list(sort_list)
。
解释:
当您在打印前更新函数内部的变量sort_list
(行-->sort_list=sort_list[half:]
)时,它更新的是与该函数调用关联的变量sort_list
,而不是全局变量sort_list
。因此,通过将返回值存储在全局变量中(如我的解决方案中所示),您的列表将得到更新,并在下次调用函数时传递更新后的列表。