Python Forum
Need to speed up my code.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Need to speed up my code.
#6
Not sure that answers OPs question. That was to print the count of the most frequent item, not the frequency of the last item in the list. By that, you would need to sort the dictionary by value and then take the last dictionary item. If you add a 3 to the end of his list, the posted code yields 3 which is incorrect - the max is still 4, based on the most frequent item (2).
Add one step, sort by value, then print which item is most frequent and that item's frequency:
lst = [3,5,2,1,2,3,2,2,3]             # list to be iterated
counts = dict()                     # dictionary for keeping counts of occurances
for item in lst:                    # iterate all list items
    try:                            # try +1 to value of key
        counts[item] += 1
    except KeyError:                # if key is not existing (raises KeyError)
        counts[item] = 1            # add key and set value to 1 (first count)
counts = sorted(counts.items(), key = lambda kv:(kv[1], kv[0]))

print(f'Most common is {counts[-1][0]} with a frequency of {counts[-1][1]}')
Reply


Messages In This Thread
Need to speed up my code. - by blackknite - Jan-14-2020, 05:04 PM
RE: Need to speed up my code. - by Gribouillis - Jan-14-2020, 06:49 PM
RE: Need to speed up my code. - by ndc85430 - Jan-15-2020, 08:36 AM
RE: Need to speed up my code. - by blackknite - Jan-19-2020, 01:24 AM
RE: Need to speed up my code. - by perfringo - Jan-19-2020, 07:57 AM
RE: Need to speed up my code. - by jefsummers - Jan-19-2020, 02:02 PM
RE: Need to speed up my code. - by perfringo - Jan-20-2020, 08:24 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020