DEV Community

Discussion on: Daily Challenge #121 - Who has the most money?

Collapse
 
rafaacioly profile image
Rafael Acioly • Edited

there is nothing more beautiful than Python

from typing import List, Union
from dataclasses import dataclass


@dataclass
class Student:

  name: str
  fives: int = 0
  tens: int = 0
  twenties: int = 0

  def __str__(self):
    return self.name

  def __eq__(self, value):
    return self._amount() == value

  def __gt__(self, value):
    return self._amount() > value

  def __lt__(self, value):
    return self._amount() < value

  def __hash__(self):
    return self._amount()

  def _amount(self):
    return sum((
      self.fives * 5,
      self.tens * 10,
      self.twenties * 20
    ))

def most_amount(students: List[Student]) -> str:
  uniques = set(students)
  return str(max(uniques)) if len(uniques) >= 2 else "all"

Usage:


student_1 = Student(name="richard", fives=25, tens=5, twenties=5)
student_2 = Student(name="helen", fives=55, tens=5, twenties=5)

print(most_amount([student_1, student_2]))  # helen
Collapse
 
hectorpascual profile image
Héctor Pascual

Hi, check this decorator :

docs.python.org/3/library/functool...

Will make you avoid writing some functions.

Collapse
 
rafaacioly profile image
Rafael Acioly

Thank you Héctor i didn't know about this.

I've tried to apply it but it looks is a little shady for me, i didn't quite understand what is does and how it "magically" does the comparison