Home > Enterprise >  Exercise Sorting Dictionaries
Exercise Sorting Dictionaries

Time:11-04

Hello, i'm gonna be really thankful if someone can tell me diffrent aproach to the task from the code below(Im sorry for my grammar, still learning english). Im looking also for advice for better writing a code, the idea for the sorting_dwarfs function didnt come on my own. Im still trying to understand fully how the sorted function works. Thank you!

Thats the task:

"You will be receiving several input lines which contain data about each dwarf in the following format:

{dwarf_name} <:> {dwarf_hat_color} <:> {dwarf_physics}

The "dwarf_name" and the "dwarf_hat_color" are strings. The "dwarf_physics" is an integer.

You must store the data about the dwarfs in your program. There are several rules though:

If 2 dwarfs have the same name but different color, they should be considered different dwarfs, and you should store them both.

If 2 dwarfs have the same name and the same color, store the one with the higher physics.

When you receive the command "Once upon a time", the input ends. You must order the dwarfs by physics in descending order and then by total count of dwarfs with the same hat color in descending order.
Then you must print them all. "

Thats the code:

def collecting_data():
    dwarfs_dict = {}
    dwarf_info = input()
    while True:
        if dwarf_info == "Once upon a time":
            return dwarfs_dict

        dwarf_name, dwarf_hat_color, dwarf_physics = dwarf_info.split(" <:> ")[0], dwarf_info.split(" <:> ")[1],\
                                                     int(dwarf_info.split(" <:> ")[2])
        if dwarf_hat_color not in dwarfs_dict:
            dwarfs_dict[dwarf_hat_color] = {dwarf_name: dwarf_physics}
        else:
            if dwarf_name not in dwarfs_dict[dwarf_hat_color]:
                dwarfs_dict[dwarf_hat_color].update({dwarf_name: dwarf_physics})
            else:
                if dwarf_physics > dwarfs_dict[dwarf_hat_color][dwarf_name]:
                    dwarfs_dict[dwarf_hat_color][dwarf_name] = dwarf_physics

        dwarf_info = input()


def sorting_dwarfs():
    dict_with_dwarfs = collecting_data()
    sorted_dwarfs = []
    for hat, info in dict_with_dwarfs.items():
        for name, physics in info.items():
            sorted_dwarfs.append({"number": len(info), "name": name, "physics": physics, "hat": hat})
    for dwarf in sorted(sorted_dwarfs, key=lambda x: (-x["physics"], -x["number"])):
        print(f"({dwarf['hat']}) {dwarf['name']} <-> {dwarf['physics']}")


sorting_dwarfs()

First I tried to sort the nested dictionary but I got a unhashbale dict error, just want to see if their is an easiest way to do the task

CodePudding user response:

A few suggestions that should be helpful in executing the code:

  • Instead of using the dwarf_color as the dictionary key, use both the dwarf_name and dwarf_color as the key.
  • at the same time, create a separate color tracker for number of dwarf_color instances.
  • This will allow you to update the dwarf_physics by simply using max(dwarf_physics, dwarf_info[dwarf_id])
  • once the dictionary is generated, sort it as per the highest physics value and dwarf color. Nested Python lists are sorted lexicopgraphically so it will take of two variables.
  • the code should look like this:
def collecting_data():
    dwarfs_dict, color_tracker = {}, {}
    
    while True:
        dwarf_info = input()
        if dwarf_info == "Once upon a time":
            return dwarfs_dict

        dwarf_name, dwarf_hat_color, dwarf_physics = dwarf_info.split(" <:> ")[0],\ 
                                                     dwarf_info.split(" <:> ")[1],\
                                                     int(dwarf_info.split(" <:> ")[2])
        dwarf_id = f"{dwarf_name} <:> {dwarf_hat_color}"

        if dwarf_hat_color not in color_tracker:
            color_tracker[dwarf_hat_color] = 1
        else:
            color_tracker[dwarf_hat_color]  = 1

        if dwarf_id not in dwarfs_dict:
            dwarfs_dict[dwarf_id] = {dwarf_id: (dwarf_physics, 
                                                color_tracker[dwarf_hat_color])}
        else:
            dwarfs_dict[dwarf_id] = {dwarf_id: (max(dwarf_physics,
                                                    dwarfs_dict[dwarf_id][0]), 
                                                color_tracker[dwarf_hat_color])}

        dwarf_info = input()


def sorting_dwarfs():
    dict_with_dwarfs = collecting_data()
    dwarf_list = list([k, v[0], v[1]] for k,v in dict_with_dwarfs.items())
    sorted_dwarfs = sorted(dwarf_list, key=lambda x: [-v[0], -v[1]])
    
    for info in sorted_dwarfs:
        print(f"{info[0]} <:> {info[1]}")



sorting_dwarfs()
  • Related