[Coding test] 8. Counter

whitehousechef·2024년 8월 5일

Counter can be equated with defaultdict

https://velog.io/@whitehousechef/Leetcode-30.-Substring-with-Concatenation-of-All-Words

They are both dictionary types so can be equated

cant use sort(). Must use sorted()

You generally don't "sort" a Counter object itself, as Counter (being a subclass of dict) is inherently unordered (prior to Python 3.7, where dicts maintain insertion order).

Also v.important, we cant pass counter object to sorted(). We need to pass counter.items() or counter.keys(), which is an iterable of (key,value) tuple form.

sorted() also returns a LIST, not a counter. so when sorting via key, it returns a list of keys, not the original counter

look at
https://velog.io/@whitehousechef/Leetcode-594.-Longest-Harmonious-Subsequence

sort by value (freq)

from collections import Counter

# Sample string (note that it contains numeric characters)
s = "9875323455"

# Step 1: Count the frequency of each character
counter = Counter(s)
print("Counter:", counter)  # Counter({'5': 3, '3': 2, '9': 1, '8': 1, '7': 1, '2': 1, '4': 1})

# Step 2: Sort by numeric keys (since they are strings, convert to int for sorting)

## wrong
sorted_by_key = sorted(counter,key=lambda x:x[1])

## correct
sorted_by_key = dict(sorted(counter.items(), key=lambda x: int(x[0])))
print("Sorted by numeric keys:", sorted_by_key)  # {'2': 1, '3': 2, '4': 1, '5': 3, '7': 1, '8': 1, '9': 1}

also look at https://leetcode.com/problems/minimum-deletions-to-make-character-frequencies-unique/

sort by the .items() and MUST USE sorted() andand not sort like regular dictionary. We just decrement the value until its a frequency value that we havent seen before. Then we add that value to our set.

need to use .items() or .values() or just the methods when turning counter or sorting counter or doing anything with it

sorted_by_key = dict(sorted(counter.items(), key=lambda x: int(x[0])))
count = list(counter.items())

#just doing list(counter) will cause error!

to sort via key, just do lambda x:x[0].

0개의 댓글