carroll
carroll

Reputation: 29

Frequencies in Python

def frequencies(data):

    data.sort()

    count = 0
    previous = data[0]

    print("data\tfrequency") # '\t' is the TAB character

    for d in data:
        if d == previous:
            # same as the previous, so just increment the count
            count += 1
        else:
            # we've found a new item so print out the old and reset the count
            print(str(previous) + "\t" + str(count))
            count = 1

        previous = d

So I have this frequency code, but its leaving off the last number in my list every time.

It may have something to do with where I start previous or possibly where I reset previous to d at the end.

Upvotes: 1

Views: 59

Answers (2)

Amadan
Amadan

Reputation: 198388

For the last group of elements, you never print them out, because you never find something different after it. You would need to repeat the printout thing after your loop.

But that is rather academic; in real world, you would be much more likely to use Counter:

from collections import Counter
counter = Counter(data)
for key in counter:
    print("%s\t%d" % (key, counter[key]))

Upvotes: 3

ojii
ojii

Reputation: 4781

You can count items in a list/sequence using count. So your code can be simplified to look like this:

def frequencies(data):
    unique_items = set(data)
    for item in unique_items:
        print('%s\t%s' % (item, data.count(item)))

Upvotes: 0

Related Questions