Skip to content

Instantly share code, notes, and snippets.

@RhettTrickett
Created August 13, 2019 19:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RhettTrickett/c2540104dce968308c9186c2cceb7f7c to your computer and use it in GitHub Desktop.
Save RhettTrickett/c2540104dce968308c9186c2cceb7f7c to your computer and use it in GitHub Desktop.
Try catch vs. if else
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