Created
August 13, 2019 19:00
-
-
Save RhettTrickett/c2540104dce968308c9186c2cceb7f7c to your computer and use it in GitHub Desktop.
Try catch vs. if else
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from timeit import default_timer as time | |
# Open text file and add each word to a list | |
with open('file.txt') as f: | |
lines = [line.strip() for line in f] | |
words = [] | |
for l in lines: | |
words.extend(l.split()) | |
# Time if/else pattern | |
start = time() | |
word_count = {} | |
for word in words: | |
if word in word_count: | |
word_count[word] += 1 | |
else: | |
word_count[word] = 1 | |
end = time() | |
duration = end - start | |
# Print out results | |
print("if/else") | |
print('{:.10f} sec'.format(duration)) | |
print('--') | |
# Clean-up variables for next count | |
del word_count, start, end, duration | |
# Time try / except pattern | |
start = time() | |
word_count = {} | |
for word in words: | |
try: | |
word_count[word] += 1 | |
except KeyError: | |
word_count[word] = 1 | |
end = time() | |
duration = end - start | |
print("try/except") | |
print('{:.10f} sec'.format(duration)) | |
print('--') | |
print(f"Total words: {len(words)}") | |
print(f'Unique words: { len(word_count) }') | |
ratio = len(word_count) / len(words) | |
print('Ratio: {:.2f}'.format(ratio)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment