Skip to content

Instantly share code, notes, and snippets.

@andyinabox
Created October 18, 2015 17:40
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 andyinabox/70dd4dc7e351279a1971 to your computer and use it in GitHub Desktop.
Save andyinabox/70dd4dc7e351279a1971 to your computer and use it in GitHub Desktop.
Word count example
import sys
# set our count variable as an empty dict
count = {}
# iterate through lines of input
for line in sys.stdin:
# strip whitespace and line breaks
line = line.strip()
# break into a list of words (break apart at spaces)
words = line.split()
# now iterate through our words
for word in words:
# if the word has already been added to the dict
# then add 1 to the stored value
if word in count:
count[word] += 1
# otherwise, add the word to the dict with value of 1
else:
count[word] = 1
# now iterate through a sorted list of the dict's keys
for word in sorted(count.keys()):
# now print the word and it's value in alpha order
print word, str(count[word])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment