The search algorithm for all divisors of the number
📁 функция, список, python, пример
Day! When deciding on the network, the algorithm for finding all the dividers of the number. Well, that is, for eight it is necessary to issue [1,2,4,8], and not [2.2,2] - a list of divisors. I rewrote this Nanovo algorithm, I ask the "senior comrades" "to tell how to improve. If there is time))
def divisors ( n ): from collections import counter ls = get_ls (n) # for n = 1568 -& gt; ls = [2, 2, 2, 2, 2, 7, 7] Pairs = dict (couter (ls)) # {2: 5, 7: 2} from itertools Import product, Starmap from oparator Import mul from funstools Import reduce # list of all different divisions of the number bass = [b for b in pairs.keys ()] # [2, 7] # list of unique divisors to obtain the number Powers = [I for i in range (k+ 1 )] for k in pairs.values ()] # generating all sets for obtaining dividers of the original number multi = product (*powers) zip (bases, power) for power in multi) # sets of numbers, sets which you need to change to obtain a divider rezzz = (Starmap ( for row in wrk) # retu List of all dividers retu [reduce (mul, i) in reziz] for example [1, 7, 49, 2, 14, 98, 4, 28, 196, 8, 56, 392, 16, 112, 784, 32, 224, 1568]
for example:
deg span> get_ls ( n ): " "" "" "" "decompose the number" "" "" " #result = [1] span> Result = [] i = 2 when i*i & lt; = n: if n % i == 0 : n n n n n n n n n n n. // = i result.ppend (i) else : i += 1 if n & gt; 1 : result.ppend (n) retu result what can be improved? ACCUMELATE from Itertools. Well, in general, according to the algorithm.
it is clear that the improvements of the type
retu [red, i) for i in (Starmap ( pow , row) for row in ( zip (bases, power) for power in product (*powers)))]
is not interesting.
Ответов пока нет.
Войдите чтобы оставить ответ
Блоги