Home > Mobile >  The count() method counts wrong
The count() method counts wrong

Time:06-09

Here is my task to solve.

For a list of integers, find and print the items that appear in the list only once. Items must be printed in the order in which they are are in the incoming list.

I wrote the code but it also counts two and three digit numbers as a single digits. What's the problem?

x = []
a = input()
a.split(" ")
for i in a:
    if a.count(i) == 1:
        x.append(i)
print(x)

CodePudding user response:

User Mechanical Pig provides the answer, split does not work in-place, since you're discarding its result what you're looking at is the count of each character in the string, not each space-separated sub-string.

The standard library also contains a collection which is ready-made for this use-case: collections.Counter. You can just give it a sequence of items and it'll collate the counts, which you can then filter:

print([k for k, v in collections.Counter(a.split()).items() if v == 1])

CodePudding user response:

a.split(" ") does not change the value of a, so it is still a string and not a list. Hence when you iterate over a, you only get single characters.

str.split is a method that returns a list, but does not magically turn the string into a list. So you need to assign the value it returns to a variable (for example, to a, if you don't want to hold on to the input string).

CodePudding user response:

You can assign the variable as mentioned above or you can directly use the split function in the loop.

x = []
a = input()
for i in a.split(" "):
    if a.count(i) == 1:
        x.append(i)
print(x)

or split when you are reading the input.

x = []
a = input().split(" ")
for i in a:
    if a.count(i) == 1:
        x.append(i)
print(x)

CodePudding user response:

Using the Counter class from the collections module is the right way to do this but here's another way without any imports where you effectively have your own limited implementation of a Counter:

a = '1 2 3 4 4 5 6 7 7 7'

d = {}

for n in a.split():
    d[n] = d.get(n, 0)   1

for k, v in d.items():
    if v == 1:
        print(k)

Output:

1
2
3
5
6
  • Related