328 http://inventwithpython.com/hacking
Email questions to the author: [email protected]
- def getUsefulFactors(num):
Returns a list of useful factors of num. By "useful" we mean factors
less than MAX_KEY_LENGTH + 1. For example, getUsefulFactors(144)
returns [2, 72, 3, 48, 4, 36, 6, 24, 8, 18, 9, 16, 12]
- if num < 2:
- return [] # numbers less than 2 have no useful factors
- factors = [] # the list of factors found
When finding factors, you only need to check the integers up to
MAX_KEY_LENGTH.
- for i in range(2, MAX_KEY_LENGTH + 1): # don't test 1
- if num % i == 0:
- factors.append(i)
- factors.append(int(num / i))
- if 1 in factors:
- factors.remove(1)
- return list(set(factors))
- def getItemAtIndexOne(x):
- return x[1]
- def getMostCommonFactors(seqFactors):
First, get a count of how many times a factor occurs in seqFactors.
- factorCounts = {} # key is a factor, value is how often if occurs
seqFactors keys are sequences, values are lists of factors of the
spacings. seqFactors has a value like: {'GFD': [2, 3, 4, 6, 9, 12,
18, 23, 36, 46, 69, 92, 138, 207], 'ALW': [2, 3, 4, 6, ...], ...}
- for seq in seqFactors:
- factorList = seqFactors[seq]
- for factor in factorList:
- if factor not in factorCounts:
- factorCounts[factor] = 0
- factorCounts[factor] += 1
Second, put the factor and its count into a tuple, and make a list
of these tuples so we can sort them.
- factorsByCount = []
- for factor in factorCounts:
exclude factors larger than MAX_KEY_LENGTH