Home > Back-end >  Function to sort a list in a specific order, while also counting the amount of times each value appe
Function to sort a list in a specific order, while also counting the amount of times each value appe

Time:10-15

So I need to define a function that returns a list that is arranged in a specific order, and also gives the amount of times each value appears.

For example, let's say i have this input:

["s", "w", "h", "s", "h"]

I'll need my function to return this:

[2, 2, 1]

The 2 is the amount of times s appears, the following 2 is the amount of times h appears, and the 1 is the amount of times w appears.

I have been stuck on this for quite a while now, this is how far I came:

def item_order(list):
    sort_order = {"s": 0, "h": 1, "w": 2}
    list.sort(key=lambda val: sort_order[val[1]])

But I'm not sure if this is the right way to go. Any help would be greatly appreciated!

CodePudding user response:

You can use collections.Counter to count number of items. For example:

from collections import Counter


def item_order(lst):
    weights = {"s": 0, "h": 1, "w": 2}
    rv = sorted(lst, key=weights.get)
    return rv, Counter(rv)


lst = ["s", "w", "h", "s", "h"]
sorted_list, cnt = item_order(lst)
print(sorted_list)
print(cnt)  # or list(cnt.values())

Prints:

['s', 's', 'h', 'h', 'w']
Counter({'s': 2, 'h': 2, 'w': 1})

CodePudding user response:

# A set for values already seen
seen_characters = set()

# Function sorts a list of characters, calculates count of unique characters
# Parameter:    list -> of characters
# Returns:   list -> of numbers 
def item_order(character_list):
    result = []
    character_list.sort()
    for character in character_list:
        if character not in seen_characters:
            result.append(character_list.count(character))
            seen_characters.add(character)
    return result

given_list = ['s', 'w', 'h', 's', 'h']
print(item_order(given_list))
  • Related