340 http://inventwithpython.com/hacking
Email questions to the author: [email protected]
dictionary value like {'VRA': [8, 2, 4, 2, 3, 4, 6, 8, 12, 16, 8, 2, 4],
'AZU': [2, 3, 4, 6, 8, 12, 16, 24], 'YBN': [8, 2, 4]}.
The getMostCommonFactors() function will find the most common factors in
seqFactors and return a list of two-integer tuples. The first integer in the tuple will be the
factor and the second integer will be how many times it was in seqFactors.
For example, getMostCommonFactors() may return a list value such as [(3, 556),
(2, 541), (6, 529), (4, 331), (12, 325), (8, 171), (9, 156), (16,
105), (5, 98), (11, 86), (10, 84), (15, 84), (7, 83), (14, 68),
(13, 52)]. This means that in the seqFactors dictionary passed to
getMostCommonFactors(), the factor 3 showed up 556 times, the factor 2 showed up 541
times, the factor 5 showed up 529 times, and so on. Note that 3 is the most frequent factor in the
list and appears first in the list. 1 3 is the least frequent factor and is last in the list.
vigenereHacker.py
88. for seq in seqFactors:
89. factorList = seqFactors[seq]
90. for factor in factorList:
91. if factor not in factorCounts:
92. factorCounts[factor] = 0
93. factorCounts[factor] += 1
For the first step of getMostCommonFactors() the for loop on line 88 loops over every
sequence in seqFactors, storing it in a variable named seq on each iteration. The list of
factors in seqFactors for seq is stored in a variable named factorList on line 89.
The factors in this list are looped over with a for loop on line 90. If a factor does not exist as a
key in factorCounts, it is added on line 92 with a value of 0. On line 93,
factorCounts[factor] (that is, the factor’s value in factorCounts) is incremented.
vigenereHacker.py
95. # Second, put the factor and its count into a tuple, and make a list
96. # of these tuples so we can sort them.
97. factorsByCount = []
98. for factor in factorCounts:
99. # exclude factors larger than MAX_KEY_LENGTH
100. if factor <= MAX_KEY_LENGTH:
101. # factorsByCount is a list of tuples: (factor, factorCount)
102. # factorsByCount has a value like: [(3, 497), (2, 487), ...]
103. factorsByCount.append( (factor, factorCounts[factor]) )