Домашни > Великденско домашно > Решения > Решението на Никита Симинкович

Резултати
6 точки от тестове
0 точки от учител

6 точки общо

46 успешни теста
0 неуспешни теста
Код
Скрий всички коментари

  1class Egg:
  2    def __init__(self):
  3        self.upper_colors = []
  4        self.upper_is_broken = False
  5        self.lower_colors = []
  6        self.lower_is_broken = False
  7        self.tournament: None | EggTournament = None
  8
  9    @property
 10    def upper_hardness(self):
 11        red = sum([int(color[0:2], 16) * percent / 50 for color, percent in self.upper_colors])
 12        green = sum([int(color[2:4], 16) * percent / 50 for color, percent in self.upper_colors])
 13        blue = sum([int(color[4:], 16) * percent / 50 for color, percent in self.upper_colors])
 14        return red + green + blue
 15    
 16    @property
 17    def lower_hardness(self):
 18        red = sum([int(color[0:2], 16) * percent / 50 for color, percent in self.lower_colors])
 19        green = sum([int(color[2:4], 16) * percent / 50 for color, percent in self.lower_colors])
 20        blue = sum([int(color[4:], 16) * percent / 50 for color, percent in self.lower_colors])
 21        return red + green + blue
 22    
 23    @property
 24    def victories(self):
 25        return list(self.tournament.fights.values()).count(self) if self.tournament else 0
 26    
 27    @property
 28    def position(self):
 29        return next(self.tournament.ranking.index(x) for x in self.tournament.ranking if self in x) + 1 if self.tournament is not None else None
 30
 31    @staticmethod
 32    def __get_percent(colors):
 33        return sum([color[1] for color in colors])
 34    
 35    def paint(self, *colors):
 36        if self.__get_percent(self.upper_colors + self.lower_colors + list(colors)) <= 100:
 37            for color in colors:
 38                if self.__get_percent(self.upper_colors) == 50:
 39                    self.lower_colors.append(color)
 40                else:
 41                    if self.__get_percent(self.upper_colors + [color]) <= 50:
 42                        self.upper_colors.append(color)  
 43                    else:
 44                        self.lower_colors.append((color[0], color[1] - (50 - self.__get_percent(self.upper_colors))))
 45                        self.upper_colors.append((color[0], 50 - self.__get_percent(self.upper_colors)))
 46        else:
 47            raise ValueError("Can't paint over 100%")
 48        
 49    def __mul__(self, other):
 50        if not self.upper_is_broken and not other.upper_is_broken:
 51            if (self.upper_hardness > other.upper_hardness) or (self.upper_colors and not other.upper_colors):
 52                other.upper_is_broken = True
 53                if self.tournament == other.tournament and self.tournament:
 54                    self.tournament.fights[(self, other, "top")] = self
 55                return self 
 56            self.upper_is_broken = True
 57            if self.tournament == other.tournament and self.tournament:
 58                self.tournament.fights[(self, other, "top")] = other
 59            return other  
 60        raise TypeError("An egg is broken on that side")
 61
 62    def __matmul__(self, other):
 63        if not self.lower_is_broken and not other.lower_is_broken:
 64            if (self.lower_hardness > other.lower_hardness) or (self.lower_colors and not other.lower_colors):
 65                other.lower_is_broken = True
 66                if self.tournament == other.tournament and self.tournament:
 67                    self.tournament.fights[(self, other, "bottom")] = self
 68                return self 
 69            self.lower_is_broken = True
 70            if self.tournament == other.tournament and self.tournament:
 71                self.tournament.fights[(self, other, "bottom")] = other
 72            return other  
 73        raise TypeError("An egg is broken on that side")
 74    
 75    # def __repr__(self):
 76    #     return f"upp {self.upper_hardness}|{self.upper_is_broken} - low {self.lower_hardness}|{self.lower_is_broken}"
 77
 78
 79class EggTournament:
 80    def __init__(self):
 81        self.eggs: dict[str, Egg] = {}
 82        self.fights = {}
 83
 84    @property
 85    def ranking(self):
 86        ranking_points = {egg:egg.victories for egg in self.eggs.values()}
 87        ranking = []
 88        for egg, points in sorted(ranking_points.items(), key=lambda egg: -egg[1]):
 89            if not ranking:
 90                ranking += [[egg]]
 91                continue
 92            if ranking_points[ranking[-1][-1]] == points:
 93                ranking[-1].append(egg)
 94            else:
 95                ranking.append([egg])
 96        return ranking
 97
 98    def register(self, egg:Egg, name: str):
 99        if egg.tournament:
100            raise ValueError("An egg cannot be registered in multiple tournaments")
101        
102        try:
103            exec(f"{name} = 0\ndel {name}")
104        except SyntaxError:
105            raise ValueError("Invalid registration name")
106        
107        if name in self.eggs.keys():
108            raise ValueError(f"Egg with name {name} has already been registered")
109        
110        self.eggs[name] = egg
111        egg.tournament = self
112
113    def __getitem__(self, key):
114        if not isinstance(key, slice):
115            first, second, side = key
116        else:
117            first = key.start
118            second = key.stop
119            side = key.step
120
121        try:
122            return self.fights[(first, second, side)]
123        except KeyError:
124            pass
125
126        try:
127            return self.fights[(second, first, side)]
128        except KeyError:
129            pass
130
131        raise KeyError("No such fight")
132    
133    def __rmatmul__(self, other):
134        try:
135            return set(self.ranking[other - 1]) if len(self.ranking[other - 1]) > 1 else self.ranking[other - 1][0]
136        except IndexError:
137            raise IndexError("No such position in the tournament")
138
139    def __getattr__(self, name: str):
140        try:
141            return {"position": self.eggs[name].position, "victories": self.eggs[name].victories}
142        except KeyError:
143            raise AttributeError("Apologies, there is no such egg registered")
144            
145    def __contains__(self, item):
146        return True if item in self.eggs.values() else False

..............................................
----------------------------------------------------------------------
Ran 46 tests in 0.002s

OK

Дискусия
История

f1f1
22
3class Egg:3class Egg:
4    def __init__(self):4    def __init__(self):
5        self.upper_colors = []5        self.upper_colors = []
6        self.upper_is_broken = False6        self.upper_is_broken = False
7        self.lower_colors = []7        self.lower_colors = []
8        self.lower_is_broken = False8        self.lower_is_broken = False
9        self.tournament: None | EggTournament = None9        self.tournament: None | EggTournament = None
1010
11    @property11    @property
12    def upper_hardness(self):12    def upper_hardness(self):
13        red = sum([int(color[0:2], 16) * percent / 50 for color, percent in self.upper_colors])13        red = sum([int(color[0:2], 16) * percent / 50 for color, percent in self.upper_colors])
14        green = sum([int(color[2:4], 16) * percent / 50 for color, percent in self.upper_colors])14        green = sum([int(color[2:4], 16) * percent / 50 for color, percent in self.upper_colors])
15        blue = sum([int(color[4:], 16) * percent / 50 for color, percent in self.upper_colors])15        blue = sum([int(color[4:], 16) * percent / 50 for color, percent in self.upper_colors])
16        return red + green + blue16        return red + green + blue
17    17    
18    @property18    @property
19    def lower_hardness(self):19    def lower_hardness(self):
20        red = sum([int(color[0:2], 16) * percent / 50 for color, percent in self.lower_colors])20        red = sum([int(color[0:2], 16) * percent / 50 for color, percent in self.lower_colors])
21        green = sum([int(color[2:4], 16) * percent / 50 for color, percent in self.lower_colors])21        green = sum([int(color[2:4], 16) * percent / 50 for color, percent in self.lower_colors])
22        blue = sum([int(color[4:], 16) * percent / 50 for color, percent in self.lower_colors])22        blue = sum([int(color[4:], 16) * percent / 50 for color, percent in self.lower_colors])
23        return red + green + blue23        return red + green + blue
24    24    
25    @property25    @property
26    def victories(self):26    def victories(self):
27        return list(self.tournament.fights.values()).count(self) if self.tournament else 027        return list(self.tournament.fights.values()).count(self) if self.tournament else 0
28    28    
29    @property29    @property
30    def position(self):30    def position(self):
31        return next(self.tournament.ranking.index(x) for x in self.tournament.ranking if self in x) + 1 if self.tournament is not None else None31        return next(self.tournament.ranking.index(x) for x in self.tournament.ranking if self in x) + 1 if self.tournament is not None else None
3232
33    @staticmethod33    @staticmethod
34    def __get_percent(colors):34    def __get_percent(colors):
35        return sum([color[1] for color in colors])35        return sum([color[1] for color in colors])
36    36    
37    def paint(self, *colors):37    def paint(self, *colors):
38        if self.__get_percent(self.upper_colors + self.lower_colors + list(colors)) <= 100:38        if self.__get_percent(self.upper_colors + self.lower_colors + list(colors)) <= 100:
39            for color in colors:39            for color in colors:
40                if self.__get_percent(self.upper_colors) == 50:40                if self.__get_percent(self.upper_colors) == 50:
41                    self.lower_colors.append(color)41                    self.lower_colors.append(color)
42                else:42                else:
43                    if self.__get_percent(self.upper_colors + [color]) <= 50:43                    if self.__get_percent(self.upper_colors + [color]) <= 50:
44                        self.upper_colors.append(color)  44                        self.upper_colors.append(color)  
45                    else:45                    else:
46                        self.lower_colors.append((color[0], color[1] - (50 - self.__get_percent(self.upper_colors))))46                        self.lower_colors.append((color[0], color[1] - (50 - self.__get_percent(self.upper_colors))))
47                        self.upper_colors.append((color[0], 50 - self.__get_percent(self.upper_colors)))47                        self.upper_colors.append((color[0], 50 - self.__get_percent(self.upper_colors)))
48        else:48        else:
49            raise ValueError("Can't paint over 100%")49            raise ValueError("Can't paint over 100%")
50        50        
51    def __mul__(self, other):51    def __mul__(self, other):
52        if not self.upper_is_broken and not other.upper_is_broken:52        if not self.upper_is_broken and not other.upper_is_broken:
53            if (self.upper_hardness > other.upper_hardness) or (self.upper_colors and not other.upper_colors):53            if (self.upper_hardness > other.upper_hardness) or (self.upper_colors and not other.upper_colors):
54                other.upper_is_broken = True54                other.upper_is_broken = True
55                if self.tournament == other.tournament and self.tournament:55                if self.tournament == other.tournament and self.tournament:
56                    self.tournament.fights[(self, other, "top")] = self56                    self.tournament.fights[(self, other, "top")] = self
57                return self 57                return self 
58            self.upper_is_broken = True58            self.upper_is_broken = True
59            if self.tournament == other.tournament and self.tournament:59            if self.tournament == other.tournament and self.tournament:
60                self.tournament.fights[(self, other, "top")] = other60                self.tournament.fights[(self, other, "top")] = other
61            return other  61            return other  
62        raise TypeError("An egg is broken on that side")62        raise TypeError("An egg is broken on that side")
6363
64    def __matmul__(self, other):64    def __matmul__(self, other):
65        if not self.lower_is_broken and not other.lower_is_broken:65        if not self.lower_is_broken and not other.lower_is_broken:
66            if (self.lower_hardness > other.lower_hardness) or (self.lower_colors and not other.lower_colors):66            if (self.lower_hardness > other.lower_hardness) or (self.lower_colors and not other.lower_colors):
67                other.lower_is_broken = True67                other.lower_is_broken = True
68                if self.tournament == other.tournament and self.tournament:68                if self.tournament == other.tournament and self.tournament:
69                    self.tournament.fights[(self, other, "bottom")] = self69                    self.tournament.fights[(self, other, "bottom")] = self
70                return self 70                return self 
71            self.lower_is_broken = True71            self.lower_is_broken = True
72            if self.tournament == other.tournament and self.tournament:72            if self.tournament == other.tournament and self.tournament:
73                self.tournament.fights[(self, other, "bottom")] = other73                self.tournament.fights[(self, other, "bottom")] = other
74            return other  74            return other  
75        raise TypeError("An egg is broken on that side")75        raise TypeError("An egg is broken on that side")
76    76    
77    # def __repr__(self):77    # def __repr__(self):
78    #     return f"upp {self.upper_hardness}|{self.upper_is_broken} - low {self.lower_hardness}|{self.lower_is_broken}"78    #     return f"upp {self.upper_hardness}|{self.upper_is_broken} - low {self.lower_hardness}|{self.lower_is_broken}"
7979
8080
81class EggTournament:81class EggTournament:
82    def __init__(self):82    def __init__(self):
83        self.eggs: dict[str, Egg] = {}83        self.eggs: dict[str, Egg] = {}
84        self.fights = {}84        self.fights = {}
8585
86    @property86    @property
87    def ranking(self):87    def ranking(self):
88        ranking_points = {egg:egg.victories for egg in self.eggs.values()}88        ranking_points = {egg:egg.victories for egg in self.eggs.values()}
89        ranking = []89        ranking = []
90        for egg, points in sorted(ranking_points.items(), key=lambda egg: -egg[1]):90        for egg, points in sorted(ranking_points.items(), key=lambda egg: -egg[1]):
91            if not ranking:91            if not ranking:
92                ranking += [[egg]]92                ranking += [[egg]]
93                continue93                continue
94            if ranking_points[ranking[-1][-1]] == points:94            if ranking_points[ranking[-1][-1]] == points:
95                ranking[-1].append(egg)95                ranking[-1].append(egg)
96            else:96            else:
97                ranking.append([egg])97                ranking.append([egg])
98        return ranking98        return ranking
9999
100    def register(self, egg:Egg, name: str):100    def register(self, egg:Egg, name: str):
101        if egg.tournament:101        if egg.tournament:
102            raise ValueError("An egg cannot be registered in multiple tournaments")102            raise ValueError("An egg cannot be registered in multiple tournaments")
103        103        
104        try:104        try:
t105            exec(f"{name} = 0")t105            exec(f"{name} = 0\ndel {name}")
106        except SyntaxError:106        except SyntaxError:
107            raise ValueError("Invalid registration name")107            raise ValueError("Invalid registration name")
108        108        
109        if name in self.eggs.keys():109        if name in self.eggs.keys():
110            raise ValueError(f"Egg with name {name} has already been registered")110            raise ValueError(f"Egg with name {name} has already been registered")
111        111        
112        self.eggs[name] = egg112        self.eggs[name] = egg
113        egg.tournament = self113        egg.tournament = self
114114
115    def __getitem__(self, key):115    def __getitem__(self, key):
116        if not isinstance(key, slice):116        if not isinstance(key, slice):
117            first, second, side = key117            first, second, side = key
118        else:118        else:
119            first = key.start119            first = key.start
120            second = key.stop120            second = key.stop
121            side = key.step121            side = key.step
122122
123        try:123        try:
124            return self.fights[(first, second, side)]124            return self.fights[(first, second, side)]
125        except KeyError:125        except KeyError:
126            pass126            pass
127127
128        try:128        try:
129            return self.fights[(second, first, side)]129            return self.fights[(second, first, side)]
130        except KeyError:130        except KeyError:
131            pass131            pass
132132
133        raise KeyError("No such fight")133        raise KeyError("No such fight")
134    134    
135    def __rmatmul__(self, other):135    def __rmatmul__(self, other):
136        try:136        try:
137            return set(self.ranking[other - 1]) if len(self.ranking[other - 1]) > 1 else self.ranking[other - 1][0]137            return set(self.ranking[other - 1]) if len(self.ranking[other - 1]) > 1 else self.ranking[other - 1][0]
138        except IndexError:138        except IndexError:
139            raise IndexError("No such position in the tournament")139            raise IndexError("No such position in the tournament")
140140
141    def __getattr__(self, name: str):141    def __getattr__(self, name: str):
142        try:142        try:
143            return {"position": self.eggs[name].position, "victories": self.eggs[name].victories}143            return {"position": self.eggs[name].position, "victories": self.eggs[name].victories}
144        except KeyError:144        except KeyError:
145            raise AttributeError("Apologies, there is no such egg registered")145            raise AttributeError("Apologies, there is no such egg registered")
146            146            
147    def __contains__(self, item):147    def __contains__(self, item):
148        return True if item in self.eggs.values() else False148        return True if item in self.eggs.values() else False
149149
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op