Hacking Secret Ciphers with Python

(Ann) #1

258 http://inventwithpython.com/hacking


Email questions to the author: [email protected]


The fast way to build a string using a list, append(), and join().


building = []
for c in 'Hello world!':
building.append(c)
building = ''.join(building)
print(building)


Using this approach for building up strings in your code will result in much faster programs. We
will be using this list-append-join process to build strings in the remaining programs of this book.


Calculating the Word Pattern


makeWordPatterns.py
11. def getWordPattern(word):
12. # Returns a string of the pattern form of the given word.
13. # e.g. '0.1.2.3.4.1.2.3.5.6' for 'DUSTBUSTER'
14. word = word.upper()
15. nextNum = 0
16. letterNums = {}
17. wordPattern = []


The getWordPattern() function takes one string argument and returns a string of that
word’s pattern. For example, if getWordPattern() were passed the string 'Buffoon' as
an argument then getWordPattern() would return the string '0.1.2.2.3.3.4'.


First, in order to make sure all the letters have the same case, line 14 changes the word parameter
to an uppercase version of itself. We then need three variables:


 nextNum stores the next number used when a new letter is found.
 letterNums stores a dictionary with keys of single-letter strings of single letters, and
values of the integer number for that letter. As we find new letters in the word, the letter and
its number are stored in letterNums.


 wordPattern will be the string that is returned from this function. But we will be building
this string one character at a time, so we will use the list-append-join process to do this. This
is why wordPattern starts as a blank list instead of a blank string.


 makeWordPatterns.py
19. for letter in word:
20. if letter not in letterNums:
21. letterNums[letter] = str(nextNum)
22. nextNum += 1

Free download pdf