From 267255262138af92e18203f11f49ea64d041ff0b Mon Sep 17 00:00:00 2001 From: Rohit Tanwar Date: Wed, 7 Feb 2018 14:03:47 +0530 Subject: [PATCH] count_by --- README.md | 30 ++++++++++++++++++++++++++++++ snippets/count_by.md | 20 ++++++++++++++++++++ tag_database | 3 ++- 3 files changed, 52 insertions(+), 1 deletion(-) create mode 100644 snippets/count_by.md diff --git a/README.md b/README.md index 10db657c7..e4c0e0f5c 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,7 @@
  • shuffle
  • spread
  • zip
  • +
  • count_by
  • ### :scroll: String @@ -489,6 +490,35 @@ zip(['a'], [1, 2], [True, False], fill_value = '_') # [['a', 1, True], ['_', 2,
    :arrow_up: Back to top +### count_by + +Groups the elements of a list based on the given function and returns the count of elements in each group. + +Use `map()` to map the values of the list using the given function. Iterate over the map and increase the the elements count each time it occurs. + +```py +def count_by(arr, fn=lambda x: x): + key = {} + for el in map(fn, arr): + key[el] = 0 if not el in key else key[el] + key[el] += 1 + return key + + ``` + +
    View Examples + +```py + +from math import floor +count_by([6.1, 4.2, 6.3], floor) # {4: 1, 6: 2} +count_by(['one', 'two', 'three'], len) # {3: 2, 5: 1} + +``` +
    + +
    :arrow_up: Back to top + ## :scroll: String ### count_vowels diff --git a/snippets/count_by.md b/snippets/count_by.md new file mode 100644 index 000000000..2b37ecd11 --- /dev/null +++ b/snippets/count_by.md @@ -0,0 +1,20 @@ +### count_by + +Groups the elements of a list based on the given function and returns the count of elements in each group. + +Use `map()` to map the values of the list using the given function. Iterate over the map and increase the the elements count each time it occurs. + +```python +def count_by(arr, fn=lambda x: x): + key = {} + for el in map(fn, arr): + key[el] = 0 if not el in key else key[el] + key[el] += 1 + return key +``` + +``` python +from math import floor +count_by([6.1, 4.2, 6.3], floor) # {4: 1, 6: 2} +count_by(['one', 'two', 'three'], len) # {3: 2, 5: 1} +``` \ No newline at end of file diff --git a/tag_database b/tag_database index 72a4fa20c..6e4cdc7a8 100644 --- a/tag_database +++ b/tag_database @@ -19,4 +19,5 @@ capitalize_every_word:string decapitalize:string palindrome:string is_upper_case:string -is_lower_case:string \ No newline at end of file +is_lower_case:string +count_by:list \ No newline at end of file