Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
Before we can use the Binary Search algorithm on our list of names, we need to sort it. Let's do that now. We need to load our unsorted list of names from a file, sort it, and write the sorted names back out to a new file.
Before we can use the Binary Search algorithm on our list of names, we need to sort it. Let's do that now. We need to load our unsorted list of names from a file, sort it, and write the sorted names back out to a new file.
# Again, this code at the top just loads a file full of strings into a list.
import sys
from load import load_strings
names = load_strings(sys.argv[1])
# We'll use our quicksort method to sort the list of names. Its code is
# completely unchanged from when you saw it in the previous stage.
def quicksort(values):
if len(values) <= 1:
return values
less_than_pivot = []
greater_than_pivot = []
pivot = values[0]
for value in values[1:]:
if value <= pivot:
less_than_pivot.append(value)
else:
greater_than_pivot.append(value)
return quicksort(less_than_pivot) + [pivot] + quicksort(greater_than_pivot)
# We just call our quicksort function on the list of names loaded from the
# file, and save the list to a variable.
sorted_names = quicksort(names)
# Then, we loop through each name in the sorted list...
for n in sorted_names:
# ...And print that name.
print(n)
- That's all there is to it! Let's try running this script.
python quicksort_strings.py names/unsorted.txt
- That prints the sorted list of names out to the terminal. But we need it in a file.
- So we'll do what's called a redirect of the program's output.
- We'll run the same command as before, but at the end we'll put a
>
greater than sign, followed by the path to a file that we want the program output written to:names/sorted.txt
- Redirecting works not only on Linux-based systems like Workspaces, but also on Macs and even on Windows machines. You just need to be careful because if you redirect to an existing file, its contents will be overwritten without asking you.
python quicksort_strings.py names/unsorted.txt > names/sorted.txt
Now we can load this file of sorted names into a list, and we'll be able to use that list with the Binary Search algorithm. We'll see how to do that next.
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up