我想打印调用Util类中的binarySearch方法,并希望返回索引值以及字符串或数字。
class Utilily :
@staticmethod
def binarySearch(arr, l, r, key): # l = low, r = high
if (r >= l):
mid = int(l + (r - l)/2)
if (arr[mid] == key):
return mid
elif (arr[mid] > key):
return (binarySearch(arr,l,mid-1,key))
else:
return (binarySearch(arr,mid+1,r,key))
else:
return -1
u = Utility()
def main():
n = int(input("Press \n 1. Binary Search Integer \n 2. Binary Search String \n 3. Exit \n"))
if n == 1:
n = int(input("Enter the Number of elements you want to insert:"))
arr = list()
print("Enter the elements:")
for i in range(n):
arr.append(int(input()))
key = int(input("Enter the Key element:"))
result = u.binarySearch(arr, 0, len(arr)-1, key)
if (result != -1):
print("Element is present at index %d" % result)
else:
print("Element is not present in array")
elif n == 2:
n = int(input("Enter the Number of elements you want to insert:"))
arr = list()
print("Enter the elements in assending order: (i.e from A-Z)")
for i in range(n):
arr.append(input())
key = input("Enter the Key element:")
result = u.binarySearch(arr, 0, len(arr)-1, key)
#print(result)
if (result != -1):
print("Element is present at index %d" % result)
else:
print("Element is not present in array")
elif n == 3:
exit()
'整数错误
Press 1. Binary Search Integer 2. Binary Search String 3. Exit 1 Enter the Number of elements you want to insert:5 Enter the elements: 1 2 3 4 5 Enter the Key element:5 Traceback (most recent call last): File "my.py", line 47, in main() File "my.py", line 26, in main result = u.binarySearch(arr, 0, len(arr)-1, key) File "my.py", line 11, in binarySearch return (binarySearch(arr,mid+1,r,key)) NameError: name 'binarySearch' is not definedBut I need an out put of "index 4"
字符串错误
Press 1. Binary Search Integer 2. Binary Search String 3. Exit 2 Enter the Number of elements you want to insert:5 Enter the elements in assending order: (i.e from A-Z) a b c d e Enter the Key element:e Traceback (most recent call last): File "my.py", line 47, in main() File "my.py", line 38, in main result = u.binarySearch(arr, 0, len(arr)-1, key) File "my.py", line 11, in binarySearch return (binarySearch(arr,mid+1,r,key)) NameError: name 'binarySearch' is not defined任何人都可以帮助我吗? 请.....'
答案 0 :(得分:0)
更改:
return (binarySearch(arr,l,mid-1,key))
收件人:
return (Utility.binarySearch(arr,l,mid-1,key))
然后更改:
return (binarySearch(arr,mid+1,r,key))
收件人:
return (Utility.binarySearch(arr,mid+1,r,key))
为什么?因为binarySearch
是在Utility
类内部声明的方法,而不是全局函数。