0

Input ->

a=[16,21, 56, 40] 
**Code I wrote**

def find_primes(a):
    num_factors=[] 
    for num in a:
       # print('1',num)
        list_of_factors=[]
        i=2
        while num>1:
            #print('2',num)
            if num%i==0:
                list_of_factors.append(i)
               # print('3',list_of_factors)
                num=num/i
               # print('4',num)
                i=i-1
                
            i+=1 
        num_factors.append(list_of_factors)  
    d = {}
    a_list = []
    for i in num_factors:
        for j in i:
            d[j] = d.get(j, 0) + 1
            dictionary_copy = d.copy()
    a_list.append(dictionary_copy)  
    print(a_list)
    return num_factors
    
find_primes(a)

This is the output I am getting:

[{2: 10, 3: 1, 7: 2, 5: 1}]
[[2, 2, 2, 2], [3, 7], [2, 2, 2, 7], [2, 2, 2, 5]]

Here is my question (Doubt to clarify on the output of my code):

Understand since it is a dictionary, the value for the key accumulates.

I want to have the count of unique integers from each list. For eg. [{2:4},{3:1,7:1},{2:3,7:1},{2:3,5:1}] instead of what is given in the output from the code above.

After which, I want to get the max occurrence for each of the integers to calculate the LCM. 2^4 * 3 * 7 * 5

Kindly advise on how we could improve on the code.Not looking for FINISHED SOLUTION.just suggestion. Appreciate the help.

For this question, we are not allowed to use gcd or any other math libraries to solve it

Ann
  • 1
  • 2
  • Then is using numpy allowed? `import numpy as np` and then `print(np.lcm.reduce(a))`. – Wasif Oct 08 '20 at 01:42
  • You are very close. Just put the line `a_list.append(dictionary_copy)` inside the first for loop and you are done – lbal Oct 08 '20 at 02:19
  • @LucíaBalestrazzi Thanks. Have tried that before too. But this is the output I get when I tried that. -> [{2: 4}, {2: 4, 3: 1, 7: 1}, {2: 7, 3: 1, 7: 2}, {2: 10, 3: 1, 7: 2, 5: 1}] – Ann Oct 08 '20 at 03:01

1 Answers1

0

this seems like a homework problem, so I won't give you a finished solution.

to get the count of distinct items in a list, an efficient solution is to convert it to a set, then find the length:

mylist = [3,3,3,4,5]
print(set(mylist))
#{3, 4, 5}
print(len(set(mylist)))
#3  


biglist = [[2, 2, 2, 2], [3, 7], [2, 2, 2, 7], [2, 2, 2, 5]]
for sublist in biglist:
    print(max(sublist))
#2
#7
#7
#5
barker
  • 1,005
  • 18
  • 36