Loading...

Във форума е въведено ограничение, което позволява на потребителите единствено да разглеждат публикуваните въпроси.

niyazihasan avatar niyazihasan 83 Точки

Snowwhite 70/100

Здравейте,

Някой може ли да помогне със сортировката на задачата?

Условието е:

Snow White loves her dwarfs, but there are so many and she doesn't know how to order them. Does she order them by name? Or by color of their hat? Or by physics? She can't decide, so its up to you to write a program that does it for her.

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

{dwarfName} <:> {dwarfHatColor} <:> {dwarfPhysics}

The dwarfName and the dwarfHatColor are strings. The dwarfPhysics is an integer.

You must store 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 both of them.
  • 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.

Input

  • The input will consists of several input lines, containing dwarf data in the format, specified above.
  • The input ends when you receive the command "Once upon a time".

Output

  • As output you must print the dwarfs, ordered in the way , specified above.
  • The output format is: ({hatColor}) {name} <-> {physics}

Constraints

  • The dwarfName will be a string which may contain any ASCII character except ' ' (space), '<', ':', '>'.
  • The dwarfHatColor will be a string which may contain any ASCII character except ' ' (space), '<', ':', '>'.
  • The dwarfPhysics will be an integer in range [0, 231 – 1].
  • There will be no invalid input lines.
  • If all sorting criteria fail, the order should be by order of input.
  • Allowed working time / memory: 100ms / 16MB.

Examples

Input

Output

Pesho <:> Red <:> 2000

Tosho <:> Blue <:> 1000

Gosho <:> Green <:> 1000

Sasho <:> Yellow <:> 4500

Prakasho <:> Stamat <:> 1000

Once upon a time

(Yellow) Sasho <-> 4500

(Red) Pesho <-> 2000

(Blue) Tosho <-> 1000

(Green) Gosho <-> 1000

(Stamat) Prakasho <-> 1000

Pesho <:> Red <:> 5000

Pesho <:> Blue <:> 10000

Pesho <:> Red <:> 10000

Gosho <:> Blue <:> 10000

Once upon a time

(Blue) Pesho <-> 10000

(Blue) Gosho <-> 10000

(Red) Pesho <-> 10000

 

 

items = input()
dwrafs = {}
while items != "Once upon a time":
    tokens = items.split(" <:> ")
    name = tokens[0]
    color = tokens[1]
    physics = int(tokens[2])
    id = name + ":" + color
    if id not in dwrafs:
        dwrafs[id] = 0
    dwrafs[id] = max([dwrafs[id], physics])
    items = input()

sorted_dwrafs = dict(sorted(dwrafs.items(), key=lambda x: x[1], reverse=True))
for key, value in sorted_dwrafs.items():
    tokens = key.split(":")
    print(f"({tokens[1]}) {tokens[0]} <-> {value}")
Тагове:
1
Fundamentals Module
MartinBG avatar MartinBG 4803 Точки
Best Answer

Един от начините за сортиране по "total count of dwarfs with the same hat color", е с използване на dictionary {color : count}, който се ъпдейтва при добавянето на ново джудже. За да го използваме по-лесно, може да пазим цвета на шапката към записа на всяко джудже, т,е, dwarfs ще е { key, [physics, color]}.

Това е решението с горните промени и уговорката, че Python не ми е основен език и може да има и по-елегантно решение на проблема:

items = input()
dwarfs = {}
colors = {}
while items != "Once upon a time":
    tokens = items.split(" <:> ")
    name = tokens[0]
    color = tokens[1]
    physics = int(tokens[2])
    id = name + ":" + color
    if id not in dwarfs:
        if color not in colors:
            colors[color] = 1
        else:
            colors[color] += 1
        dwarfs[id] = [0, color]
    dwarfs[id][0] = max([dwarfs[id][0], physics])
    items = input()

sorted_dwrafs = dict(sorted(dwarfs.items(), key=lambda x: (x[1][0], colors[x[1][1]]), reverse=True))
for key, value in sorted_dwrafs.items():
    tokens = key.split(":")
    print(f"({tokens[1]}) {tokens[0]} <-> {value[0]}")

 

1
16/06/2020 22:28:14
niyazihasan avatar niyazihasan 83 Точки

Благодаря Ви за съдействието

1
vigyriousx avatar vigyriousx 10 Точки

Бихте ли обяснили как colors[x[1][1]] работи точно? Опитах се с nested dicts да реша задачката, но точно заради тези шапки минах на друга логика.

0
MartinBG avatar MartinBG 4803 Точки

@vigyriousx

x се достъпва като двумерен масив: x[ id, [physics, color]]

x[0] връща id-то

x[1] ни дава достъп до елеметите на [physics, color]

x[1][0] връща първия елемент, който в случая е physics

x[1][1] връща втория елемент, който в случая е color

С други думи, colors[x[1][1]]  ще върне броя джуджета с цвета на джуджето, което се сортира в момента.

 

 

0
vigyriousx avatar vigyriousx 10 Точки

Благодаря!

1
Можем ли да използваме бисквитки?
Ние използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Можете да се съгласите с всички или част от тях.
Назад
Функционални
Използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Използваме „сесийни“ бисквитки, за да Ви идентифицираме временно. Те се пазят само по време на активната употреба на услугите ни. След излизане от приложението, затваряне на браузъра или мобилното устройство, данните се трият. Използваме бисквитки, за да предоставим опцията „Запомни Ме“, която Ви позволява да използвате нашите услуги без да предоставяте потребителско име и парола. Допълнително е възможно да използваме бисквитки за да съхраняваме различни малки настройки, като избор на езика, позиции на менюта и персонализирано съдържание. Използваме бисквитки и за измерване на маркетинговите ни усилия.
Рекламни
Използваме бисквитки, за да измерваме маркетинг ефективността ни, броене на посещения, както и за проследяването дали дадено електронно писмо е било отворено.