Literally need correction in only one line of the code below. Everything in the code works fine except for line: dwarfs.sort(key=lambda x:-x.physics)
which is incomplete.
After creating the objects and appending them in the list dwarfs
and keeping track of the colors in the colors
dictionary I want to sort the objects by: self.physics
and then, if multiple with the same value, by appearance of the color
in colors
dictionary.
With my current code when entering
Grumpy <:> Red <:> 5000
Grumpy <:> Blue <:> 10000
Grumpy <:> Red <:> 10000
Happy <:> Blue <:> 10000
Once upon a time
I would like to receive:
(Blue) Grumpy <-> 10000
(Blue) Happy <-> 10000
(Red) Grumpy <-> 10000
Instead I have:
(Blue) Grumpy <-> 10000
(Red) Grumpy <-> 10000
(Blue) Happy <-> 10000
Code:
class Dwarf:
def __init__(self,name,hat_color,physics:int):
self.name=name
self.hat_color=hat_color
self.physics=physics
def __repr__(self):
return f"({self.hat_color}) {self.name} <-> {self.physics}"
dwarfs=[]
colors={}
while True:
entry=input()
if entry=="Once upon a time":
break
name,hat_color,physics=entry.split(" <:> ")
physics=int(physics)
obj=Dwarf(name,hat_color,physics)
tracker=None
if len(dwarfs)==0:
dwarfs.append(obj)
else:
for i in dwarfs:
if name==i.name and hat_color==i.hat_color:
tracker=i
break
if tracker!= None:
dwarfs.remove(tracker)
dwarfs.append(obj)
if hat_color not in colors:
colors[hat_color]=1
else:
if tracker is None:
colors[hat_color]+=1
colors={k:v for k,v in sorted(colors.items(),key=lambda x:-x[1])}
dwarfs.sort(key=lambda x:-x.physics)
for dwarf in dwarfs:
print(dwarf)