问题
I am having trouble getting this binary sort to work. I get syntax errors at lower_bound
and in other places. I know it is something obvious but I am getting to the desk flipping point. Can someone help me to get this to run clearly, I know this is basic stuff but I am fairly new to this.
def main():
sortNames()
binarySearch()
def sortNames():
global names
names = ["Chris Rich", "Ava Fischer", "Bob White", "Danielle Porter", "Gordon Pike", "Hannah Beauregard", "Matt Hoyle", "Ross Harrison", "Sasha Ricci", "Xavier Adams"]
names.sort()
def binarySearch():
global names, found, nameSearch, lower_bound, middle_pos, upper_bound
nameSearch = string(input("What name are you looking for?")
lower_bound = 0
upper_bound = len(names)-1
found = False
while lower_bound <= upper_bound and not found:
middle_pos = (lower_bound+upper_bound) // 2
if name_list[middle_pos] < nameSearch:
lower_bound = middle_pos + 1
elif name_list[middle_pos] > nameSearch:
upper_bound = middle_pos - 1
else:
found = True
if found:
print("The name is at position", middle_pos)
else:
print("The name was not in the list.")
main()
回答1:
You forgot to add the last closing parenthesis on the preceding line:
nameSearch = string(input("What name are you looking for?")
# 1--^ 2--^ 2--^
Also, you didn't define the function string()
. Not that it is needed, input()
returns a string already.
After that, I see an error for name_list
, but presumably you have that list defined outside of the code posted here.
回答2:
names = ["Chris Rich", "Ava Fischer", "Bob White",\
"Danielle Porter", "Gordon Pike", "Hannah Beauregard",\
"Matt Hoyle", "Ross Harrison", "Sasha Ricci", "Xavier Adams"]
def sortNames():
global names
names.sort()
def binarySearch():
global names, found, nameSearch, lower_bound, middle_pos, upper_bound
nameSearch = raw_input("What name are you looking for?")
lower_bound = 0
upper_bound = len(names)-1
found = False
while lower_bound <= upper_bound and not found:
middle_pos = (lower_bound+upper_bound) // 2
if names[middle_pos] < nameSearch:
lower_bound = middle_pos + 1
elif names[middle_pos] > nameSearch:
upper_bound = middle_pos - 1
else:
found = True
if found:
print("The name is at position", middle_pos)
else:
print("The name was not in the list.")
def main():
sortNames()
binarySearch()
if __name__ == "__main__":
main()
Output
anukalp@anukalp-Latitude-E6400:~$ python del1.py
What name are you looking for?Ross Harrison
('The name is at position', 7)
来源:https://stackoverflow.com/questions/19896239/binary-string-search-in-python-3-x