From 9e76e8f67f913d6e2c3532fece5e549fd49758cf Mon Sep 17 00:00:00 2001 From: Azan Bin Zahid <47540683+azanbinzahid@users.noreply.github.com> Date: Sat, 3 Oct 2020 18:50:18 +0500 Subject: [PATCH] Imrove frequencies snippet implementation (#234) Co-authored-by: Isabelle Viktoria Maciohsek --- snippets/frequencies.md | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/snippets/frequencies.md b/snippets/frequencies.md index 9e16a8ea8..91dc18eda 100644 --- a/snippets/frequencies.md +++ b/snippets/frequencies.md @@ -5,16 +5,12 @@ tags: list,intermediate Returns a dictionary with the unique values of a list as keys and their frequencies as the values. -- Use a `for` loop to populate a dictionary, `f`, with the unique values in `lst` as keys, adding to existing keys every time the same value is encountered. +- Use `list.count()` to get the frequency of each unique element. +- Use `dict()` constructor to return a dictionary with the unique elements of the list as keys and their frequencies as the values. ```py -from functools import reduce - def frequencies(lst): - f = {} - for x in lst: - f[x] = f[x] + 1 if x in f else 1 - return f + return dict((k, lst.count(k)) for k in lst) ``` ```py