Assume you are creating a webshop and you would like to help the user in the search. You have products with brands, prices and name. You have the history of opened products (the most recently opened being the first item).

Your task is to create a list of brands ordered by popularity, if two brands have the same popularity level then choose the one which was opened last from the two and second the other one.

Product popularity is calculated from the history. If a product is more times in the history than it is more popular.

Your function will have one parameter which will be always an array/list of object.

example product:
{
  name: "Phone",
  price: 25,
  brand: "Fake brand"
}

Difficulty: introductory

Starter code:

def sorted_brands(history):
	

Solutions:
from collections import Counter

def sorted_brands(history):
    brands = [x['brand'] for x in history]
    counter = Counter(brands)
    return sorted(set(brands), key=lambda x: (-counter[x], brands.index(x)))

def sorted_brands(history):
    brands = [item['brand'] for item in history]
    return sorted(set(brands), key=lambda x: (-brands.count(x), brands.index(x)))

from collections import Counter


def sorted_brands(history):
    brands = Counter(x["brand"] for x in history)
    return [brand for brand, _ in brands.most_common()]

from collections import Counter

def sorted_brands(history):
    cnt = Counter(item["brand"] for item in history)
    return sorted(cnt, key=cnt.get, reverse=True)

def sorted_brands(history):
    count = {}
    for i in history:
        count[i['brand']] = count.get(i['brand'],0)+1
    return sorted(count,key=lambda x:-count[x])

from collections import Counter

def sorted_brands(history):
    picked, c = {}, Counter()
    for i,h in enumerate(history):
        c[h['brand']] += 1
        if h['brand'] not in picked: picked[h['brand']] = i
    return sorted(c, key=lambda k: (-c[k], picked[k]))

from collections import Counter
def sorted_brands(history):
    return [n[0] for n in Counter([n['brand'] for n in history]).most_common()]
    



def sorted_brands(history):
    d = {}
    for i in history:
        if i['brand'] in d:
            d[i['brand']] += 1
        else:
            d[i['brand']] = 1
    return sorted(list(d.keys()), key=lambda x: d[x], reverse=True)
        


def sorted_brands(arr):
    arr = [k['brand'] for k in arr]
    return sorted(set(arr), key=lambda x: (-arr.count(x), arr.index(x)))

def sorted_brands(history):
    s = [i['brand'] for i in history]
    print(s)
        
    return sorted(set(s), key=lambda x: (-s.count(x), s.index(x)))