I wrote some code (Python) that prints that expresses a number in prime numbers. Here is the code that I have:
n = 24
lst=[]
i = 2
while n>1:
if n%i==0:
lst.append(i)
n=n/i
i-=1
i+=1
print(lst)
For example when my n
is 24
, the output from the list is [2,2,2,3]
, because 2*2*2*3=24
. Now I want to make a list that gives how many times a number occurs in my list. So for this example I want that my output is: [3,1]
, because 2 occurs 3 times in my list en 3 occurs one time in my list. I have no idea how I can do this. When I uses the function count(), it prints [3,3,3,1]
, because it checks the other list and checks for each item in it how often it exists, so also for the second and third item, which is the same as the first. Does anyone know how my code must look in order to have the output [3,1]
?
There's a datatype called a Counter in the standard library. Given an input iterable, it will output a dictionary of { value: count of value }
pairs. You can use it as follows (output is from the ipython REPL):
In [1]: from collections import Counter
In [2]: primes = [2,2,2,3]
In [3]: counts = Counter(primes)
In [4]: counts
Out[4]: Counter({2: 3, 3: 1})
In [5]: counts.values()
Out[5]: dict_values([3, 1])
In [6]: list(counts.values())
Out[6]: [3, 1]
For illustrative purposes, let's also construct this manually using a defaultdict:
In [7]: from collections import defaultdict
In [8]: counts = defaultdict(int)
In [9]: for p in primes:
...: counts[p] += 1
...:
In [10]: counts
Out[10]: defaultdict(int, {2: 3, 3: 1})
In [11]: counts.values()
Out[11]: dict_values([3, 1])
In [12]: list(counts.values())
Out[12]: [3, 1]
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments