Chalarangelo / 30-seconds-of-python

Short Python code snippets for all your development needs

Home Page:https://www.30secondsofcode.org/python/p/1

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[FEATURE] count_by() could be improved.

rpural opened this issue · comments

[FEATURE] REPLACE THIS WITH A BRIEF SUMMARY OF THE SUGGESTED SNIPPET

Category:

Description

The current code used in count_by() needlessly sets the key value to itself. It could be more efficient and more straight-forward if changed.

Current Snippet Behavior

The current code:

def count_by(arr, fn=lambda x: x):
key = {}
for el in map(fn, arr):
key[el] = 0 if el not in key else key[el]
key[el] += 1
return key

Possible Solution

My suggested replacement:

def count_by(arr, fn=lambda x: x):
key = {}
for el in map(fn, arr):
key[el] = 1 if el not in key else key[el] + 1
return key

commented

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for any follow-up tasks.