Skip to content

Instantly share code, notes, and snippets.

@Antrikshy
Last active August 29, 2015 14:00
Show Gist options
  • Save Antrikshy/6bf5ac799bdb46d37310 to your computer and use it in GitHub Desktop.
Save Antrikshy/6bf5ac799bdb46d37310 to your computer and use it in GitHub Desktop.
Python script to count the number of ways letters in a string (passed in as argument) can be rearranged
# USAGE: python Letter_Permutations.py <string here>
# Do not put spaces between multiple words in the string
import argparse
import math
# Reads word from argument
parser = argparse.ArgumentParser()
parser.add_argument('word', help = "Word to count combinations for")
args = parser.parse_args()
# Converts all letters to lowercase for consistency
word = (args.word).lower()
# Numerator of final formula
wordLength = len(word)
numerator = math.factorial(wordLength)
# List containing all letters of the word
wordArray = list(word)
# Number of times each letter occurs stored in list
letterOccurances = list()
# List of letters that have been counted in wordArray
countedLetters = list()
# Loops through wordArray, counts how many times a letter occurs, skips over
# already counted letters using a list of such letters (list updated each time)
for letter in wordArray:
if letter in countedLetters:
continue
letterOccurances.append(wordArray.count(letter))
countedLetters.append(letter)
# Denominator of final formula
denominator = 1
for i in letterOccurances:
denominator = (denominator * math.factorial(i))
# Result
print "Number of permutations: " + str(numerator/denominator)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment