Sunday, June 12, 2016

Problem Solving with Python

Last year I took over the task of finding short messages for the sign out in front of my church building. It's not a particularly frequent or regular task; I usually try to find something new to put up approximately every 2–4 weeks.

Now:
  1. The church building is only about 3/4 mile from my house.
  2. In an effort to get more exercise I prefer to walk there to change the sign (usually in the cool of the evening) rather than driving.
  3. This makes carrying the box containing all the letters impractical, as it's just a bit too large and unwieldy to carry that far by hand.
  4. However, carrying only the letters required (usually a few dozen) is pretty easy.
This all leads to me needing to figure out how many of each letter I'm going to need to take with me every few weeks. This week I finally got tired of counting manually and dashed off a quick script I can use in the future. It's pretty simple, so I figured I'd post here for anyone interested. I've tried to comment it pretty thoroughly (a lot more thoroughly than I normally do, if I'm honest).

#!/usr/bin/python3

# Script to print the number of each letter in a given string.
from string import ascii_uppercase, ascii_letters
import argparse

# Use the argparse module to handle command line arguments.
parser = argparse.ArgumentParser(description='Count letters in a string.')

# Add an argument for the string to be read and counted.
parser.add_argument('count_string', type=str, action='store',
                    help='The string to count the letters in.')
args = parser.parse_args()

# Take the command line argument and convert it to an uppercase
# string.
input_string = args.count_string.upper()

# Create a variable to track the number of letters:
total = 0
for character in input_string:
    # Check if each character is a letter, and update the total if so.
    if character in ascii_letters:
        total += 1

# Check against each uppercase character:
for char1 in ascii_uppercase:
    # Create a variable to store the number of this particular character.
    num = 0
    for char2 in input_string:
        # Check each character in the input against the given character in the
        # list. If they match, increment the variable by 1.
        if char1 == char2:
            num += 1

    if num > 0: # Don't bother reporting zero occurrences.
        # Print the results for the character.
        print("# of {letter}'s: {number}".format(number=num, letter=char1))

print('------')
print('Total number of letters: {0}'.format(total))

exit(0)


A typical output looks like this:

$ char_count 'A simple string to test the new script!'
# of A's: 1
# of C's: 1
# of E's: 4
# of G's: 1
# of H's: 1
# of I's: 3
# of L's: 1
# of M's: 1
# of N's: 2
# of O's: 1
# of P's: 2
# of R's: 2
# of S's: 4
# of T's: 6
# of W's: 1
------
Total number of letters: 31

For the script syntax highlighting I'm trying out this Javascript libary I found called SyntaxHighlighter. It unfortunately doesn't show up while previewing the post, but seems to work well enough in the finished posted product.

2 comments:

  1. #!/usr/bin/env python

    import string

    s = 'The answer to the ultimate question of life, the universe, and everthing is 42.'

    for c in list(string.printable):
    n = s.count(c)
    if n != 0:
    print c, n

    ReplyDelete
    Replies
    1. Nice, very compact! It even tells you how many spaces there are.

      Delete

Think I said something interesting or insightful? Let me know what you thought! Or even just drop in and say "hi" once in a while - I always enjoy reading comments.