338 http://inventwithpython.com/hacking
Email questions to the author: [email protected]
parameter and returns a list of “useful” factors. The function does not necessarily return all the
factors of num in this list.
Line 6 1 checks for the special case where num is less than 2. In this case, line 6 2 returns the
empty list because these numbers have no useful factors.
vigenereHacker.py
66. # When finding factors, you only need to check the integers up to
67. # MAX_KEY_LENGTH.
68. for i in range(2, MAX_KEY_LENGTH + 1): # don't test 1
69. if num % i == 0:
70. factors.append(i)
71. factors.append(int(num / i))
The for loop on line 68 loops through the integers 2 up to MAX_KEY_LENGTH (including the
value in MAX_KEY_LENGTH itself, since the second argument to range() is
MAX_KEY_LENGTH + 1).
If num % i is equal to 0 , then we know that i evenly divides (that is, has 0 remainder) num and
is a factor of num. In this case, line 7 0 appends i to the list of factors in the factors variable.
Line 7 1 also appends num / i (after converting it from a float to an int, since the / operator
always evaluates to a float value).
vigenereHacker.py
- if 1 in factors:
- factors.remove(1)
The value 1 is not a useful factor, so we remove it from the factors list. (If the Vigenère key
had a length of 1, the Vigenère cipher would be no different from the Caesar cipher!)
Removing Duplicates with the set() Function
vigenereHacker.py
74. return list(set(factors))
The factors list might contain duplicates. For example, if getUsefulFactors() was
passed 9 for the num parameter, then 9 % 3 == 0 would be True and both i and int(num
/ i) (both of which evaluate to 3 ) would have been appended to factors. But we don’t want
duplicate numbers to appear in our factors list.
Line 74 passes the list value in factors to set() which returns a set form of the list. The set
data type is similar to the list data type, except a set value can only contain unique values. You