user9814201
user9814201

Reputation:

Adding unique integers

Write a Python program that reads an integer that gives the number of integers to be read and then reads these integers, one per line, into a list. Print the total of these integers except that if an integer appears more than once it will not be counted.

You may not use the count method of lists. For example, the input:

• 5 1 2 3 4 5 would give 15;

• 5 1 2 3 4 2 would give 8;

• 5 1 2 1 4 2 would give 4; and

• 5 2 2 2 2 2 would give 0.

My code works but is a little hard to read, anyways to so simply this without imports?

xs = [int(input()) for i in range(int(input()))] 
print(sum([xs[i] for i in range(len(xs)) \ if xs[i] not in xs[:i] + xs[i + 1:]]))

Upvotes: 0

Views: 45

Answers (1)

Patrick Haugh
Patrick Haugh

Reputation: 61032

Split the counting and summing steps. Do one pass over the list to determine the unique elements, then another to sum them.

from collections import Counter

def sum_unique(inputs):
    counts = Counter(inputs)
    return sum(num for num, count in counts.items() if count == 1)

xs = [int(input()) for i in range(int(input()))] 
print(sum_unique(xs))

Edit: Sorry, I didn't see "without imports". You can make a regular dict act like a Counter, it's just not as pretty.

def sum_unique(inputs):
    counts = {}
    for x in inputs:
        counts[x] = counts.get(x, 0) + 1
    return sum(num for num, count in counts.items() if count == 1)

Upvotes: 1

Related Questions