python - Update list to include new elements of another list (primefactor computation) -



python - Update list to include new elements of another list (primefactor computation) -

calculating prime factors numbers contained in list numbers. returned helper-method primefactors_of_number list. want maintain track of of them (e.g. in list all_factors , have them in right quantity).

as example, input

class="lang-python prettyprint-override">[12,16,17]

find_all_primefactors should homecoming

class="lang-python prettyprint-override">[2,2,3,2,2,17]

in order.

the point makes me problems update all_factors contain 2 4 times.

here code far:

class="lang-python prettyprint-override">def find_all_primefactors(list_with_numbers): prime_factors = [] all_factors = [] number in list_with_numbers: prime_factors = primefactors_of_number(number) # missing part: # update all_factors in way contains elements of prime_factors @ to the lowest degree in same quantity homecoming all_factors def primefactors_of_number(number): ''' returns primefactors of specified number list ''' i=2 prime_factors=[] while i<=number: while number%i==0: prime_factors.append(i) number/=i i+=1 homecoming prime_factors

i think solve lot of looping , temporary values, assume there more elegant solution.

here's suggestion how modify first function:

def find_all_primefactors(list_with_numbers): all_factors = [] number in list_with_numbers: prime_factors = primefactors_of_number(number) x in set(prime_factors): # loop on factors without duplicates in_all = all_factors.count(x) # how many x in all_factors in_p = prime_factors.count(x) # how many x in prime_factors diff = in_p - in_all all_factors.extend([x]*diff) # extend all_factors based on difference # note [x]*diff [] diff <= 0 homecoming all_factors

primefactors_of_number stays same. output

print(find_all_primefactors([12,16,17]))

is

[2, 2, 3, 2, 2, 17]

python list

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -