如何将 return 值分配给 python 中的变量?
How do you assign a return value to a variable in python?
我一直在研究二进制插入排序,我遇到了 problem.It 一直告诉我
"NoneType' object cannot be interpreted as an integer" 在第二个 for 循环之前的 "binary_insertion_sort" 函数处。任何人都可以解释我的代码有什么问题并告诉我其中是否有任何逻辑错误?
def binary_search(n, bin_list, low, high):
print(low,high)
if high - low <= 1:
if n < bin_list[low]:
return low - 1
elif n > bin_list[high]:
print('d',n,high)
return high + 1
elif n == bin_list[low]:
return low
elif n== bin_list[high]:
return high
else:
print('c',low)
return low+1
mid = (low+high)//2
print('a',mid)
if n < bin_list[mid]:
binary_search(n, bin_list, 0, mid-1)
elif n > bin_list[mid]:
binary_search(n, bin_list, mid+1, high)
else:
return mid
binary_insertion_sort部分
def binary_insertion_sort(text):
sorted_list = text.split()
for num in range(1, len(sorted_list)):
unsorted = sorted_list[num]
print(sorted_list)
index = binary_search(unsorted, sorted_list, 0, len(sorted_list)-1)
for j in range(num, index, -1):
print(j)
sorted_list[j] = sorted_list[j-1]
sorted_list[index-1] = num
return sorted_list
a = binary_insertion_sort('1 2 3 4 5')
我认为您缺少 binary_search 函数中递归情况的 return。
如函数在最后进入前两种情况之一 if:
if n < bin_list[mid]:
binary_search(n, bin_list, 0, mid-1)
elif n > bin_list[mid]:
binary_search(n, bin_list, mid+1, high)
else:
return mid
您正在将 None(函数 return 类型)分配给索引变量。您应该尝试使用:
if n < bin_list[mid]:
return binary_search(n, bin_list, 0, mid-1)
elif n > bin_list[mid]:
return binary_search(n, bin_list, mid+1, high)
else:
return mid
我一直在研究二进制插入排序,我遇到了 problem.It 一直告诉我 "NoneType' object cannot be interpreted as an integer" 在第二个 for 循环之前的 "binary_insertion_sort" 函数处。任何人都可以解释我的代码有什么问题并告诉我其中是否有任何逻辑错误?
def binary_search(n, bin_list, low, high):
print(low,high)
if high - low <= 1:
if n < bin_list[low]:
return low - 1
elif n > bin_list[high]:
print('d',n,high)
return high + 1
elif n == bin_list[low]:
return low
elif n== bin_list[high]:
return high
else:
print('c',low)
return low+1
mid = (low+high)//2
print('a',mid)
if n < bin_list[mid]:
binary_search(n, bin_list, 0, mid-1)
elif n > bin_list[mid]:
binary_search(n, bin_list, mid+1, high)
else:
return mid
binary_insertion_sort部分
def binary_insertion_sort(text):
sorted_list = text.split()
for num in range(1, len(sorted_list)):
unsorted = sorted_list[num]
print(sorted_list)
index = binary_search(unsorted, sorted_list, 0, len(sorted_list)-1)
for j in range(num, index, -1):
print(j)
sorted_list[j] = sorted_list[j-1]
sorted_list[index-1] = num
return sorted_list
a = binary_insertion_sort('1 2 3 4 5')
我认为您缺少 binary_search 函数中递归情况的 return。
如函数在最后进入前两种情况之一 if:
if n < bin_list[mid]:
binary_search(n, bin_list, 0, mid-1)
elif n > bin_list[mid]:
binary_search(n, bin_list, mid+1, high)
else:
return mid
您正在将 None(函数 return 类型)分配给索引变量。您应该尝试使用:
if n < bin_list[mid]:
return binary_search(n, bin_list, 0, mid-1)
elif n > bin_list[mid]:
return binary_search(n, bin_list, mid+1, high)
else:
return mid