Reputation: 1464
This code counts the number of pairs in a list and returns the total number of pairs:
ar = [10, 20, 20, 10, 10, 30, 50, 10, 20]
parsed = []
total_pairs = 0
for i in ar:
# if a list item has been parsed, put it in this list
# so that it does not reoccur
if i in parsed:
continue
else:
# if it's a new item, append it to parsed list
parsed.append(i)
# if there is only one item, skip it:
if ar.count(i) == 1:
continue
else:
# count the number of pairs
pairs = ar.count(i) // 2
# add this to the total number of pairs
total_pairs = total_pairs + pairs
print(total_pairs)
It is expected to return 3, but the output is:
2
3
I can't understand where the 2
is coming from.
Upvotes: 1
Views: 45
Reputation: 26335
Adding to the other answers, you could also use collections.Counter
to count the total number of pairs:
>>> from collections import Counter
>>> ar = [10, 20, 20, 10, 10, 30, 50, 10, 20]
>>> sum(v // 2 for v in Counter(ar).values())
3
Or using the fast collections.defaultdict
:
from collections import defaultdict
ar = [10, 20, 20, 10, 10, 30, 50, 10, 20]
counts = defaultdict(int)
for item in ar:
counts[item] += 1
print(sum(v // 2 for v in counts.values()))
# 3
Upvotes: 2
Reputation: 33159
print(total_pairs)
is inside the loop. Simply move it after the loop:
total_pairs = total_pairs + pairs
print(total_pairs)
BTW you can simplify the loop:
for i in ar:
if i in parsed:
continue
parsed.append(i)
if ar.count(i) == 1:
continue
total_pairs += ar.count(i) // 2
And FWIW you can do the whole thing more easily with a Counter
:
from collections import Counter
counts = Counter(ar)
total_pairs = sum(i//2 for i in counts.values())
print(total_pairs) # -> 3
Upvotes: 2
Reputation: 5058
It's an indentation issue.
ar = [10, 20, 20, 10, 10, 30, 50, 10, 20]
parsed = []
total_pairs = 0
for i in ar:
# if a list item has been parsed, put it in this list
# so that it does not reoccur
if i in parsed:
continue
else:
# if it's a new item, append it to parsed list
parsed.append(i)
# if there is only one item, skip it:
if ar.count(i) == 1:
continue
else:
# count the number of pairs
pairs = ar.count(i) // 2
# add this to the total number of pairs
total_pairs = total_pairs + pairs
print(total_pairs) # This should be outside the loop.
Upvotes: 2