Reputation: 748
I have seen this and this. I was wondering if I could do it without using libraries like collection, but with a simple loop structure. Can I do this in Python?
void printRepeating(int arr[], int size)
{
int *count = (int *)calloc(sizeof(int), (size - 2));
int i;
printf(" Repeating elements are ");
for(i = 0; i < size; i++)
{
if(count[arr[i]] == 1)
printf(" %d ", arr[i]);
else
count[arr[i]]++;
}
}
I tried doing this -
a=[1,2,3,2,4,3,1,7,4,3];
b=[];
for i in a:
b[i]=b[i]+1;
But I get
IndexError: list index out of range
Is there a way around it?
Upvotes: 0
Views: 10215
Reputation: 6009
Welcome to Python world, you C developer! ;) You can drop the semicolons here.
Your b
here is a Python list with 0 elements, you cannot get or set elements inside it this way: b[i]
if an element with index i does not exist already.
But there are plenty of ways to do what you want. If you really don't want to use built-in libraries, you can try this way (should produce the exact same output as your C code):
a = [1,2,3,2,4,3,1,7,4,3]
print("Repeating elements are")
for i in a:
if a.count(i) > 1:
print(i)
But a collections.Counter
is the best way to do it, it is built-in so why not use it ?
from collections import Counter
a = [1,2,3,2,4,3,1,7,4,3]
counter = Counter(a)
print(counter.most_common())
Upvotes: 4
Reputation: 73480
Using a dict
(Python's built-in hash map type) will be the simplest:
a = [1,2,3,2,4,3,1,7,4,3]
b = {}
for i in a:
# get(key, default) falls back to default if key is not present
b[i] = b.get(i, 0) + 1
> b
{1: 2, 2: 2, 3: 3, 4: 2, 7: 1}
> b[3]
3
Upvotes: 5
Reputation: 859
If I understood you correctly, you are creating b
as a list to count the occurrences of each of the numbers in a
. That way, you can create a dictionary that might be easier:
a=[1,2,3,2,4,3,1,7,4,3]
b={}
for i in a:
if i in b:
b[i]+=1
else:
b[i]=1
And then go through the dictionary to check for repeats.
Upvotes: 2