· 6 years ago · Dec 10, 2019, 12:40 PM
1Марк Бессонов, сегодня в 14:24
2Mall
3Oluline on, et kasutaksite importimisel täpselt sellist kuju: import filter. Selleks, et see töötaks, tehke järgmist
4
5kopeerige pr04_filter kausta alt filter.py fail pr08_testing kausta.
6tehke pr08_testing kaustal parem klikk "Mark Directory as" > "Source Root".
7Selle tulemusena mõistab PyCharm, et pr08_testing kaust sisaldab lähtekoodi ning oskab importida filter.py samast kaustast.
8
9Funktsioone, mis testivad koodi, peab kindlasti olema rohkem kui üks ning testida tuleb ka kasutades randomit.
10
11Mall: filter_tests.py:
12
13import pytest
14import filter
15import random
16
17def test_remove_vowels_when_no_vowels():
18 pass
19
20# TODO: add more functions
21
22Марк Бессонов, сегодня в 14:24
23Mall
24"""Recursion is recursion."""
25
26
27def recursive_reverse(s: str) -> str:
28 """Reverse a string using recursion.
29
30 recursive_reverse("") => ""
31 recursive_reverse("abc") => "cba"
32
33 :param s: string
34 :return: reverse of s
35 """
36 pass
37
38
39def remove_nums_and_reverse(string):
40 """
41 Recursively remove all the numbers in the string and return reversed version of that string without numbers.
42
43 print(remove_nums_and_reverse("poo")) # "oop"
44 print(remove_nums_and_reverse("3129047284")) # empty string
45 print(remove_nums_and_reverse("34e34f7i8l 00r532o23f 4n5oh565ty7p4")) # "python for life"
46 print(remove_nums_and_reverse(" k 4")) # " k "
47
48 :param string: given string to change
49 :return: reverse version of the original string, only missing numbers
50 """
51 pass
52
53
54def task1(string):
55 """
56 Figure out what this code is supposed to do and rewrite it using recursion.
57
58 :param string: given string
59 :return: figure it out
60 """
61 for i in range(len(string)):
62 if string[i] != string[len(string) - i - 1]:
63 return False
64 return True
65
66
67def task2(string):
68 """
69 Figure out what this code is supposed to do and rewrite it using iteration.
70
71 :param string: given string
72 :return: figure it out
73 """
74 if len(string) < 2:
75 return string
76 elif string[0] == string[1]:
77 return string[0] + "-" + task2(string[1:])
78 return string[0] + task2(string[1:])
79
80Марк Бессонов, сегодня в 14:25
81Mall
82"""Let's count calories!"""
83
84
85def x_sum_loop(nums, x) -> int:
86 """
87 Given a list of integers and a number called x. Iteratively return sum of every x'th number in the list.
88
89 In this task "indexing" starts from 1, so if x = 2 and nums = [2, 3, 4, -9], the output should be -6 (3 + -9).
90
91 X can also be negative, in that case indexing starts from the end of the list, see examples below.
92
93 If x is 0, the sum should be 0 as well.
94
95 print(x_sum_loop([], 3)) # 0
96 print(x_sum_loop([2, 5, 6, 0, 15, 5], 3)) # 11
97 print(x_sum_loop([0, 5, 6, -5, -9, 3], 1)) # 0
98 print(x_sum_loop([43, 90, 115, 500], -2)) # 158
99 print(x_sum_loop([1, 2], -9)) # 0
100 print(x_sum_loop([2, 3, 6], 5)) # 0
101 print(x_sum_loop([6, 5, 3, 2, 9, 8, 6, 5, 4], 3)) # 15
102
103 :param nums: list of integer
104 :param x: number indicating every which num to add to sum
105 :return: sum of every x'th number in the list
106 """
107 pass
108
109
110def x_sum_recursion(nums, x) -> int:
111 """
112 Given a list of integers and a number called x. Recursively return sum of every x'th number in the list.
113
114 In this task "indexing" starts from 1, so if x = 2 and nums = [2, 3, 4, -9], the output should be -6 (3 + -9).
115
116 X can also be negative, in that case indexing starts from the end of the list, see examples below.
117
118 If x = 0, the sum should be 0 as well.
119
120 print(x_sum_recursion([], 3)) # 0
121 print(x_sum_recursion([2, 5, 6, 0, 15, 5], 3)) # 11
122 print(x_sum_recursion([0, 5, 6, -5, -9, 3], 1)) # 0
123 print(x_sum_recursion([43, 90, 115, 500], -2)) # 158
124 print(x_sum_recursion([1, 2], -9)) # 0
125 print(x_sum_recursion([2, 3, 6], 5)) # 0
126 print(x_sum_recursion([6, 5, 3, 2, 9, 8, 6, 5, 4], 3)) # 15
127
128 :param nums: list of integer
129 :param x: number indicating every which num to add to sum
130 :return: sum of every x'th number in the list
131 """
132 pass
133
134
135def lets_count_calories(salad: float, chocolate_pieces: int, fridge_visits: int) -> int:
136 """
137 Every time Kadri goes to fridge, she wants to eat something. In case she has salad in her fridge, she eats exactly 100g
138 of it, no matter what. If she has chocolate in the fridge and she had just eaten salad, she takes one piece of
139 chocolate. In case she came to fridge and didn't have any salad to eat, she takes two pieces of chocolate (if she
140 has at least two pieces, if she doesn't, she takes just one). She keeps on going to the fridge for a little snack until
141 she either runs out of fridge visits or snacks.
142
143 Eating 100g of salad gives her 120 calories, eating a piece of chocolate gives her 34 calories.
144
145 Your job is to count recursively how many calories she eats at total during her fridge visits.
146
147 Salad will always be given one decimal place after comma, for an example 5.7, but never like 3.87.
148
149 print(lets_count_calories(0.1, 3, 2)) # 120 + 3*34 = 222
150 print(lets_count_calories(0.4, 3, 2)) # 2*120 + 2*34 = 308
151 print(lets_count_calories(0, 4, 2)) # 4 * 34 = 136
152 print(lets_count_calories(3.4, 6, 0)) # 0
153 print(lets_count_calories(1.2, 5, 10)) # 1200 + 5*34 = 1370
154 print(lets_count_calories(0.3, 8, 6)) # 360 + 3*34 + 2*34 + 2*34 + 34 = 632
155
156 :param salad: salad in the fridge, given in kilograms (1.2kg == 1200g).
157 :param chocolate_pieces: pieces of chocolate in the fridge.
158 :return: calories eaten while visiting fridge.
159 """
160 pass
161
162
163def cycle(cyclists: list, distance: float, time: int = 0, index: int = None) -> str:
164 """
165 Given cyclists and distance in kilometers, find out who crosses the finish line first. Cyclists is list of tuples,
166 every tuple contains name of the cyclist, how many kilometres this cyclist carries the others and time in minutes
167 showing how long it cycles first. If there are no cyclists or distance is 0 or less, return message "Everyone fails."
168 else return the last cyclist to carry others and total time taken to cross the finish line, including the last cyclist's
169 "over" minutes: "{cyclist1} is the last leader. Total time: {hours}h {minutes}min."
170 We'll say if a cyclist has cycled its kilometres ahead of the others, it's the next cyclist's turn. If the last
171 cyclist
172
173Марк Бессонов, сегодня в 14:25
174has done the leading, it's time for the first one again.
175
176 print(cycle([("First", 0.1, 9), ("Second", 0.1, 8)], 0.3)) # "First is the last leader. Total time: 0h 26min."
177 print(cycle([], 0)) # "Everyone fails."
178 print(cycle([("Fernando", 19.8, 42), ("Patricio", 12, 28), ("Daniel", 7.8, 11), ("Robert", 15.4, 49)], 50)) # "Robert is the last leader. Total time: 2h 10min."
179 print(cycle([("Loner", 0.1, 1)], 60)) # "Loner is the last leader. Total time: 10h 0min."
180
181 :param cyclists: list on tuples, containing cyclist's name, distance it cycles first and time in minutes how long it takes it.
182 :param distance: distance to be cycled overall
183 :param time: time in minutes indicating how long it has taken cyclists so far
184 :param index: index to know which cyclist's turn it is to be first
185 :return: string indicating the last cyclist to carry the others
186 """
187 pass
188
189
190def count_strings(data: list, pos=None, result: dict = None) -> dict:
191 """
192 You are given a list of strings and lists, which may also contain strings and lists etc. Your job is to
193 collect these strings into a dict, where key would be the string and value the amount of occurrences of that string
194 in these lists.
195
196 print(count_strings([[], ["J", "*", "W", "f"], ["j", "g", "*"], ["j", "8", "5", "6", "*"], ["*", "*", "A", "8"]]))
197 # {'J': 1, '*': 5, 'W': 1, 'f': 1, 'j': 2, 'g': 1, '8': 2, '5': 1, '6': 1, 'A': 1}
198 print(count_strings([[], [], [], [], ["h", "h", "m"], [], ["m", "m", "M", "m"]])) # {'h': 2, 'm': 4, 'M': 1}
199 print(count_strings([])) # {}
200 print(count_strings([['a'], 'b', ['a', ['b']]])) # {'a': 2, 'b': 2}
201
202 :param data: given list of lists
203 :param pos: figure out how to use it
204 :param result: figure out how to use it
205 :return: dict of given symbols and their count
206 """
207 pass
208
209Марк Бессонов, сегодня в 14:25
210Mall
211"""PR11 Drawing."""
212
213
214# TODO: You should create the exception classes here.
215
216
217class DrawingCanvas:
218 """A drawing canvas where one can draw some simple figures."""
219
220 def __init__(self, max_figures: int, author: str):
221 """
222 Initialize the canvas.
223
224 You should initialize your variables (properties) here.
225
226 :param max_figures: The maxim amount of figures on the drawing.
227 :param author: The author of the drawing.
228 """
229 pass
230
231 def draw_figure(self, figure: str) -> str or None:
232 """
233 Draw a new figure.
234
235 If the drawing has already reached maximum amount of figures
236 don't add this figure and throw a DrawingFullError with the
237 message "The drawing is full".
238
239 There can be only unique figures on the drawing.
240 This means that there is no way that, for example, two or more
241 circles are on the drawing.
242 In this case method does nothing and returns None.
243
244 :param figure: A figure to draw.
245 :return: The newly drawn figure.
246 """
247 pass
248
249 def erase_figure(self, figure: str) -> str:
250 """
251 Erase the figure.
252
253 If there is no such figure throw a FigureDoesNotExistError
254 with the message "There is no such figure on the drawing".
255
256 :return: The erased figure.
257 """
258 pass
259
260 def is_empty(self) -> bool:
261 """
262 Find out whether the drawing is empty or not.
263
264 Empty means there are not any figures drawn on it.
265
266 :return: True if empty, False otherwise.
267 """
268 pass
269
270 def size(self) -> int:
271 """Return the amount of figures on the drawing."""
272 pass
273
274 def __str__(self):
275 """
276 A string representation of the drawing.
277
278 The returned string must follow this pattern:
279 "The drawing painted by {author}. Contains {current amount of figures} figure(s)"
280
281 :return: A correct string representing the drawing.
282 """
283 pass
284
285
286if __name__ == '__main__':
287 dc = DrawingCanvas(5, "Person")
288
289 print("Check attributes:")
290 try:
291 print(dc.max_figures) # -> 5
292 print(dc.author) # -> Person
293 print(dc.figures) # -> Empty data structure (it depends on which one you have chose)
294 except AttributeError:
295 print("Not all of the required attributes are defined")
296 exit()
297
298 print()
299 print("Canvas after creation:")
300 print(dc.is_empty()) # -> True
301 print(dc.size()) # -> 0
302 print(dc.figures) # -> Empty data structure (it depends on which one you have chose)
303
304 print()
305 print("Draw figures:")
306 print(dc.draw_figure("circle")) # -> circle
307 print(dc.draw_figure("triangle")) # -> triangle
308 print(dc.draw_figure("Mona Lisa")) # -> Mona Lisa
309 print(dc.draw_figure("circle")) # -> None
310
311 print()
312 print("After drawing:")
313 print(dc.size()) # -> 3
314 print(dc.is_empty()) # -> False
315 print(dc.figures) # -> Data structure containing 1 circle, 1 triangle and 1 Mona Lisa
316 print(dc) # -> The drawing painted by Person. Contains 3 figure(s)
317
318 print()
319 print("Draw figures when canvas is full:")
320 try:
321 dc.draw_figure("1")
322 dc.draw_figure("2")
323 dc.draw_figure("3")
324 except DrawingFullError as e:
325 print(e) # -> The drawing is full
326 else:
327 print("The drawing is full, but exception wasn't thrown")
328 exit()
329 print(dc.size()) # -> 5
330 print(dc.figures) # -> Data structure containing circle, triangle, Mona Lisa, 1, 2
331
332 print()
333 print("Erase figures:")
334 dc.erase_figure("1")
335 dc.erase_figure("2")
336
337 print(dc.erase_figure("triangle")) # -> triangle
338 print(dc.figures) # -> Data structure containing circle and Mona Lisa
339 print(dc.size()) # -> 2
340
341 print(dc.erase_figure("Mona Lisa")) # -> Mona Lisa
342 print(dc.figures) # -> Data structure containing only circle
343 print(dc.size()) # -> 1
344
345 print(dc.erase_figure("circle")) # -> circle
346 print(dc.figures) # -> Empty data structure
347
348 print()
349 print("After erasing:")
350 print(dc.is_empty()) # -> True
351 print(dc.size()) # -> 0
352 print(dc) # -> The drawing painted by Person. Contains 0 figure(s)
353
354 print()
355 print("Erase non-existing figure:")
356 try:
357 dc.erase_figure("circle")
358 except FigureDoesNotExistError as e:
359 print(e) # -> There is no such figure on the drawing
360 else:
361 print("There is no such figure, but exception wasn't thrown.")
362
363Марк Бессонов, сегодня в 14:25
364Mall
365Fail Gitis: ex11_order/order.py
366
367"""Order system."""
368
369
370class OrderItem:
371 """Order Item requested by a customer."""
372
373 def __init__(self, customer: str, name: str, quantity: int, one_item_volume: int):
374 """
375 Constructor that creates an order item.
376
377 :param customer: requester name.
378 :param name: the name of the item.
379 :param quantity: quantity that shows how many such items customer needs.
380 :param one_item_volume: the volume of one item.
381 """
382 self.customer = customer
383 self.name = name
384 self.quantity = quantity
385 self.one_item_volume = one_item_volume
386
387 @property
388 def total_volume(self) -> int:
389 """
390 Calculate and return total volume of the current order item.
391
392 :return: Total volume (cm^3), int.
393 """
394 return self.quantity * self.one_item_volume
395
396
397class Order:
398 """Combination of order items of one customer."""
399
400 def __init__(self, order_items: list):
401 """
402 Constructor that creates an order.
403
404 :param order_items: list of order items.
405 """
406 pass
407
408 @property
409 def total_quantity(self) -> int:
410 """
411 Calculate and return the sum of quantities of all items in the order.
412
413 :return: Total quantity as int.
414 """
415 return 0
416
417 @property
418 def total_volume(self) -> int:
419 """
420 Calculate and return the total volume of all items in the order.
421
422 :return: Total volume (cm^3) as int.
423 """
424 return 0
425
426
427class Container:
428 """Container to transport orders."""
429
430 # define constructor
431
432 # define volume left property method
433 pass
434
435
436class OrderAggregator:
437 """Algorithm of aggregating orders."""
438
439 def __init__(self):
440 """
441 Initialize order aggregator.
442 """
443 self.order_items = []
444
445 def add_item(self, item: OrderItem):
446 """
447 Add order item to the aggregator.
448
449 :param item: Item to add.
450 :return: None
451 """
452 pass
453
454 def aggregate_order(self, customer: str, max_items_quantity: int, max_volume: int):
455 """
456 Create an order for customer which contains order lines added by add_item method.
457
458 Iterate over added orders items and add them to order if they are for given customer
459 and can fit to the order.
460
461 :param customer: Customer's name to create an order for.
462 :param max_items_quantity: Maximum amount on items in order.
463 :param max_volume: Maximum volume of order. All items volumes must not exceed this value.
464 :return: Order.
465 """
466 items = []
467 # collect items to the order here
468 return Order(items)
469
470
471class ContainerAggregator:
472 """Algorithm to prepare containers."""
473
474 def __init__(self, container_volume: int):
475 """
476 Initialize Container Aggregator.
477
478 :param container_volume: Volume of each container created by this aggregator.
479 """
480 pass
481
482 def prepare_containers(self, orders: tuple) -> dict:
483 """
484 Create containers and put orders to them.
485
486 If order cannot be put to a container, it is added to self.not_used_orders list.
487
488 :param orders: tuple of orders.
489 :return: dict where keys are destinations and values are containers to that destination with orders.
490 """
491 return {}
492
493
494if __name__ == '__main__':
495 print("Order items")
496
497 order_item1 = OrderItem("Apple", "iPhone 11", 100, 10)
498 order_item2 = OrderItem("Samsung", "Samsung Galaxy Note 10", 80, 10)
499 order_item3 = OrderItem("Mööbel 24", "Laud", 300, 200)
500 order_item4 = OrderItem("Apple", "iPhone 11 Pro", 200, 10)
501 order_item5 = OrderItem("Mööbel 24", "Diivan", 20, 200)
502 order_item6 = OrderItem("Mööbel 24", "Midagi väga suurt", 20, 400)
503
504 print(order_item3.total_volume) # 60000
505
506 print("Order Aggregator")
507 oa = OrderAggregator()
508 oa.add_item(order_item1)
509 oa.add_item(order_item2)
510 oa.add_item(order_item3)
511 oa.add_item(order_item4)
512 oa.add_item(order_item5)
513 oa.add_item(order_item6)
514 print(f'Added {len(oa.order_items)}(6 is correct) order items')
515
516 order1 = oa.aggregate_order("Apple", 350, 3000)
517 order1.destination = "Tallinn"
518 print(f'order1 has {len(order1.order_items)}(2 is correct) order items')
519
520 order2 = oa.aggregate_order("Mööbel 24", 325, 64100)
521 order2.destination = "Tallinn"
522 print(f'order2 has {len(order2.order_items)}(2 is correct) order items')
523
524Марк Бессонов, сегодня в 14:25
525print(f'after orders creation, aggregator has only {len(oa.order_items)}(2 is correct) order items left.')
526
527 print("Container Aggregator")
528 ca = ContainerAggregator(70000)
529 too_big_order = Order([OrderItem("Apple", "Apple Car", 10000, 300)])
530 too_big_order.destination = "Somewhere"
531 containers = ca.prepare_containers((order1, order2, too_big_order))
532 print(f'prepare_containers produced containers to {len(containers)}(1 is correct) different destination(s)')
533
534 try:
535 containers_to_tallinn = containers['Tallinn']
536 print(f'volume of the container to tallinn is {containers_to_tallinn[0].volume}(70000 is correct) cm^3')
537 print(f'container to tallinn has {len(containers_to_tallinn[0].orders)}(2 is correct) orders')
538 except KeyError:
539 print('Container to Tallinn not found!')
540 print(f'{len(ca.not_used_orders)}(1 is correct) cannot be added to containers')
541
542Марк Бессонов, сегодня в 14:25
543Mall ja näited:
544Selleks, et saaksid kiiremini progema hakata, on osa mallist ette antud. Meetodite kirjeldused ja stiili pead korda tegema.
545
546from math import pi
547
548class Chef:
549 def __init__(self, name: str, experience_level: int):
550 self.name = name
551 self.experience_level = experience_level
552
553
554class Pizza:
555 def __init__(self, name: str, diameter: int, toppings: list):
556 self.name = name
557 self.diameter = diameter
558 self.toppings = toppings
559
560 def calculate_complexity(self) -> int:
561 pass
562
563 def calculate_price(self) -> int:
564 pass
565
566
567class Pizzeria:
568 def __init__(self, name: str, is_fancy: bool, budget: int):
569 self.name = name
570 self.is_fancy = is_fancy
571 self.budget = budget
572
573 def add_chef(self, chef: Chef) -> Chef or None:
574 pass
575
576 def remove_chef(self, chef: Chef):
577 pass
578
579 def add_pizza_to_menu(self, pizza: Pizza):
580 pass
581
582 def remove_pizza_from_menu(self, pizza: Pizza):
583 pass
584
585 def bake_pizza(self, pizza: Pizza) -> Pizza or None:
586 pass
587
588 def get_pizza_menu(self) -> list:
589 pass
590
591 def get_baked_pizzas(self) -> dict:
592 pass
593
594 def get_chefs(self) -> list:
595 pass
596
597
598if __name__ == '__main__':
599 pizzeria1 = Pizzeria("Mama's Pizza", True, 10000)
600 print(pizzeria1) # Mama's pizza with 0 pizza chef(s).
601
602 pizzeria1.add_chef(Chef("Clara", 24))
603 print(pizzeria1)
604 # Mama's pizza with 0 pizza chef(s). -> Clara was not added because of low XP (24) since it's a fancy pizzeria.
605
606 pizza1 = Pizza("basic", 20, ["Cheese", "Ham"])
607 print(pizzeria1.bake_pizza(pizza1)) # None -> No such pizza on the menu nor a chef in the pizzeria.
608
609 ##########################################################
610 sebastian = Chef("Sebastian", 58)
611 charles = Chef("Charles", 35)
612 kimi = Chef("Kimi", 83)
613
614 pizzeria1.add_chef(sebastian)
615 pizzeria1.add_chef(charles)
616 pizzeria1.add_chef(kimi)
617
618 # Trying to order a pizza which is not on the menu.
619
620 print(pizzeria1.bake_pizza(pizza1)) # None
621
622 pizzeria1.add_pizza_to_menu(pizza1) # Price is 8.85
623
624 print(pizzeria1.budget) # 9115
625 print(pizzeria1.get_pizza_menu()) # [Basic pizza with a price of 8.85]
626
627 print(pizzeria1.bake_pizza(pizza1)) # Basic pizza with a price of 8.85
628
629 print(pizzeria1.get_chefs())
630 # Charles was chosen to bake the pizza, because Charles' XP was the closest to pizza's complexity
631
632 print(pizzeria1.budget) # 10887
633 print(charles.money) # 1772
634
635 print(pizzeria1.get_baked_pizzas()) # {Basic pizza with a price of 8.85: 1}
636
637 ##########################################################
638 pizzeria2 = Pizzeria("Maranello", False, 10000)
639
640 fernando = Chef("Fernando", 9)
641 felipe = Chef("Felipe", 6)
642 michael = Chef("Michael", 17)
643 rubens = Chef("Rubens", 4)
644 eddie = Chef("Eddie", 5)
645
646 pizzeria2.add_chef(fernando)
647 pizzeria2.add_chef(felipe)
648 pizzeria2.add_chef(michael)
649 pizzeria2.add_chef(rubens)
650 pizzeria2.add_chef(eddie)
651
652 margherita = Pizza("Margherita", 20, ["Sauce", "Mozzarella", "Basil"])
653 smoke = Pizza("Big Smoke", 30, ["nine", "NINE", "six w/dip", "seven", "45", "45 w/cheese", "SODA"])
654
655 pizzeria2.add_pizza_to_menu(margherita)
656 pizzeria2.add_pizza_to_menu(smoke)
657
658 print(pizzeria2.get_pizza_menu()) # [Big smoke pizza with a price of 20.67, Margherita pizza with a price of 8.85]
659 print(pizzeria2.get_chefs())
660 # [Pizza chef Rubens with 4 XP, Pizza chef Eddie with 5 XP, Pizza chef Felipe with 6 XP, Pizza chef Fernando with 9 XP, Pizza chef Michael with 17 XP]
661
662 pizzeria2.bake_pizza(margherita)
663 print(pizzeria2.get_chefs())
664 # [Pizza chef Rubens with 4 XP, Pizza chef Felipe with 6 XP, Pizza chef Fernando with 9 XP, Pizza chef Eddie with 10 XP, Pizza chef Michael with 17 XP]
665
666 pizzeria2.bake_pizza(smoke)
667 print(pizzeria2.get_chefs())
668 # [Pizza chef Rubens with 4 XP, Pizza chef Felipe with 6 XP, Pizza chef Fernando with 9 XP, Pizza chef Eddie with 14 XP, Pizza chef Michael with 17 XP]
669Grades
670Grade name Your points
671Total: 0p / 5p
672pr12_pizzeria testid 0p / 5p
673pr12_pizzeria stiil 0p / 1p
674pr12_pizzeria kaitsmine 0p / 1p
675Deadlines
676After Percentage Group
67724/11/2019 23:59 50% All groups
67801/12/2019
679[Ссылка]
680Self
681http://self.is
682
683Марк Бессонов, сегодня в 14:25
684Mall
685"""Deck."""
686from typing import Optional, List
687import requests
688
689
690class Card:
691 """Simple dataclass for holding card information."""
692
693 def __init__(self, value: str, suit: str, code: str):
694 """Constructor."""
695
696 def __str__(self):
697 """Str."""
698 return ""
699
700 def __repr__(self) -> str:
701 """Repr."""
702 return ""
703
704 def __eq__(self, o) -> bool:
705 """Eq."""
706 return False
707
708
709class Deck:
710 """Deck."""
711
712 DECK_BASE_API = "https://deckofcardsapi.com/api/deck/"
713
714 def __init__(self, deck_count: int = 1, shuffle: bool = False):
715 """Constructor."""
716 self._backup_deck = []
717 self.remaining = -1
718 pass
719
720 def shuffle(self) -> None:
721 """Shuffle the deck."""
722 pass
723
724 def draw_card(self, top_down: bool = False) -> Optional[Card]:
725 """
726 Draw card from the deck.
727
728 :return: card instance.
729 """
730 pass
731
732 def _request(self, url: str) -> dict:
733 """Update deck."""
734 pass
735
736 @staticmethod
737 def _generate_backup_pile() -> List[Card]:
738 """Generate backup pile."""
739 return []
740
741
742if __name__ == '__main__':
743 d = Deck(shuffle=True)
744 print(d.remaining) # 52
745 card1 = d.draw_card() # Random card
746 print(card1 in d._backup_deck) # False
747 print(d._backup_deck) # 51 shuffled cards
748 d2 = Deck(deck_count=2)
749 print(d2._backup_deck) # 104 ordered cards (deck after deck)
750
751Марк Бессонов, сегодня в 14:26
752Mall
753"""Blackjack."""
754import importlib
755import os
756import pkgutil
757import random
758
759from deck import Deck, Card
760from game_view import GameView, FancyView, Move
761from strategy import Strategy, HumanStrategy
762
763
764class Hand:
765 """Hand."""
766
767 def __init__(self, cards: list = None):
768 """Init."""
769 pass
770
771 def add_card(self, card: Card) -> None:
772 """Add card to hand."""
773 pass
774
775 def double_down(self, card: Card) -> None:
776 """Double down."""
777 pass
778
779 def split(self):
780 """Split hand."""
781 pass
782
783 @property
784 def can_split(self) -> bool:
785 """Check if hand can be split."""
786 pass
787
788 @property
789 def is_blackjack(self) -> bool:
790 """Check if is blackjack"""
791 pass
792
793 @property
794 def is_soft_hand(self):
795 """Check if is soft hand."""
796 pass
797
798 @property
799 def score(self) -> int:
800 """Get score of hand."""
801 pass
802
803
804class Player:
805 """Player."""
806
807 def __init__(self, name: str, strategy: Strategy, coins: int = 100):
808 """Init."""
809 pass
810
811 def join_table(self):
812 """Join table."""
813 pass
814
815 def play_move(self, hand: Hand) -> Move:
816 """Play move."""
817 pass
818
819 def split_hand(self, hand: Hand) -> None:
820 """Split hand."""
821 pass
822
823
824class GameController:
825 """Game controller."""
826
827 PLAYER_START_COINS = 200
828 BUY_IN_COST = 10
829
830 def __init__(self, view: GameView):
831 """Init."""
832 pass
833
834 def start_game(self) -> None:
835 """Start game."""
836 pass
837
838 def play_round(self) -> bool:
839 """Play round."""
840 pass
841
842 def _draw_card(self, top_down: bool = False) -> Card:
843 """Draw card."""
844
845 @staticmethod
846 def load_strategies() -> list:
847 """
848 Load strategies.
849 @:return list of strategies that are in same package.
850 DO NOT EDIT!
851 """
852 pkg_dir = os.path.dirname(__file__)
853 for (module_loader, name, is_pkg) in pkgutil.iter_modules([pkg_dir]):
854 importlib.import_module(name)
855 return list(filter(lambda x: x.__name__ != HumanStrategy.__name__, Strategy.__subclasses__()))
856
857
858if __name__ == '__main__':
859 game_controller = GameController(FancyView())
860 game_controller.start_game()
861 while game_controller.play_round():
862 pass
863strategy.py
864"""Strategy."""
865from abc import abstractmethod
866from game_view import GameView, Move
867
868
869class Strategy:
870 """Strategy."""
871
872 def __init__(self, other_players: list, house, decks_count: int):
873 """Init."""
874 self.player = None
875 self.house = house
876 self.decks_count = decks_count
877 self.other_players = other_players
878
879 @abstractmethod
880 def on_card_drawn(self, card) -> None:
881 """Called every time when card is drawn."""
882
883 @abstractmethod
884 def play_move(self, hand) -> Move:
885 """Play move."""
886
887 @abstractmethod
888 def on_game_end(self) -> None:
889 """Called on game end."""
890
891
892class HumanStrategy(Strategy):
893 """Human strategy."""
894
895 def __init__(self, other_players: list, house, decks_count, view: GameView):
896 """Init."""
897 super().__init__(other_players, house, decks_count)
898 self.view = view
899
900 def play_move(self, hand) -> Move:
901 """Play move."""
902 return self.view.ask_move()
903
904 def on_card_drawn(self, card) -> None:
905 """Called every time card is drawn."""
906
907 def on_game_end(self) -> None:
908 """Called on game end."""
909
910
911class MirrorDealerStrategy(Strategy):
912 """Very simple strategy."""
913
914 def play_move(self, hand) -> Move:
915 """Get next move."""
916 if hand.score < 17 or hand.is_soft_hand and hand.score < 18:
917 return Move.HIT
918 return Move.STAND
919
920 def on_card_drawn(self, card) -> None:
921 """Called every time card is drawn."""
922
923 def on_game_end(self) -> None:
924 """Called on game end."""
925game_view.py
926"""Game views."""
927from abc import abstractmethod
928from enum import Enum
929
930class Color:
931 """
932 Colors class.
933
934 reset all Color with Color.reset
935 two subclasses Fg for foreground and Bg for background.
936 use as Color.subclass.colorname.
937 i.e. Color.Fg.red or Color.Bg.green
938 also, the generic bold, disable, underline, reverse, strike_through,
939 and invisible work with the main class
940 i.e. Color.bold
941 """
942
943 reset = '\033[0m'
944 bold = '\033[01m'
945 disable = '\033[02m'
946 underline = '\033[04m'
947 reverse = '\033[07m'
948 strike_through = '\033[09m'
949 invisible =
950
951Марк Бессонов, сегодня в 14:26
952'\033[08m'
953
954 class Fg:
955 black = '\033[30m'
956 red = '\033[31m'
957 green = '\033[32m'
958 orange = '\033[33m'
959 blue = '\033[34m'
960 purple = '\033[35m'
961 cyan = '\033[36m'
962 light_grey = '\033[37m'
963 dark_grey = '\033[90m'
964 light_red = '\033[91m'
965 light_green = '\033[92m'
966 yellow = '\033[93m'
967 light_blue = '\033[94m'
968 pink = '\033[95m'
969 light_cyan = '\033[96m'
970
971 class Bg:
972 black = '\033[40m'
973 red = '\033[41m'
974 green = '\033[42m'
975 orange = '\033[43m'
976 blue = '\033[44m'
977 purple = '\033[45m'
978 cyan = '\033[46m'
979 light_grey = '\033[47m'
980
981
982class Move(Enum):
983 """Moves."""
984
985 HIT = "HIT",
986 STAND = "STAND",
987 SPLIT = "SPLIT",
988 DOUBLE_DOWN = "DOUBLE DOWN",
989 SURRENDER = "SURRENDER"
990
991 @staticmethod
992 def from_str(string: str):
993 """Get move from string."""
994 if string.lower() in ('hit', 'h'):
995 return Move.HIT
996 elif string.lower() in ('stand', 's'):
997 return Move.STAND
998 elif string.lower() in ('split', 'x'):
999 return Move.SPLIT
1000 elif string.lower() in ('double down', 'double', 'd'):
1001 return Move.DOUBLE_DOWN
1002 elif string.lower() in ('surrender', 'q'):
1003 return Move.SURRENDER
1004 else:
1005 raise ValueError("Invalid string input!")
1006
1007
1008class GameView:
1009 """Game View."""
1010
1011 @abstractmethod
1012 def ask_move(self) -> Move:
1013 """Ask for user input for next move."""
1014 pass
1015
1016 @abstractmethod
1017 def ask_decks_count(self) -> int:
1018 """Ask decks count."""
1019 pass
1020
1021 @abstractmethod
1022 def ask_players_count(self) -> int:
1023 """Ask human players count."""
1024 pass
1025
1026 @abstractmethod
1027 def ask_bots_count(self) -> int:
1028 """Ask bots count."""
1029 pass
1030
1031 @abstractmethod
1032 def ask_name(self, player_nr: int) -> str:
1033 """Ask player to pick name."""
1034 pass
1035
1036 @abstractmethod
1037 def show_table(self, players: list, house, player) -> None:
1038 """Show table."""
1039 pass
1040
1041 @abstractmethod
1042 def show_help(self):
1043 """Show help."""
1044 pass
1045
1046
1047class SimpleView(GameView):
1048 """Simple view."""
1049
1050 def ask_move(self) -> Move:
1051 """Ask move."""
1052 while True:
1053 try:
1054 action = Move.from_str(input("Choose your next move hit(H) or stand(S) > "))
1055 return action
1056 except ValueError:
1057 print("Invalid command! Use 'help' for help")
1058
1059 def ask_decks_count(self) -> int:
1060 """Ask decks count."""
1061 while True:
1062 count = input("Please enter decks count: ")
1063 if count.isdigit():
1064 return int(count)
1065 else:
1066 print("Value must be numeric!")
1067
1068 def ask_players_count(self) -> int:
1069 """Ask players count."""
1070 while True:
1071 count = input("Please enter human players count: ")
1072 if count.isdigit():
1073 return int(count)
1074 else:
1075 print("Value must be numeric!")
1076
1077 def ask_bots_count(self) -> int:
1078 """Ask bots count."""
1079 while True:
1080 count = input("Please enter bots count: ")
1081 if count.isdigit():
1082 return int(count)
1083 else:
1084 print("Value must be numeric!")
1085
1086 def ask_name(self, player_nr: int) -> str:
1087 """Ask player to pick name."""
1088 return input(f"Enter name for player {player_nr}: ")
1089
1090 def show_table(self, players: list, house, player) -> None:
1091 """Print table."""
1092 print('-' * 60)
1093 print("Players: Coins: Hands:")
1094 for p in players:
1095 print(f"{p.name: <20} |{p.coins: >6}|: {' | '.join(' '.join([str(c) for c in h.cards]) for h in p.hands)}")
1096 print(f"Dealer: {' '.join([str(c) for c in house.cards])}")
1097
1098 def show_help(self):
1099 """Show help."""
1100 print(f"""help -> help (print help/commands to console)
1101 hit (h) -> hit (get one more card)
1102 stand (s) -> stand (stop getting more cards, give turn to next player)
1103 split (x) -> split cards (if you have 2 cards with same value you can split them to 2 different decks)
1104 double (d) -> double down (double your bet and receive 1 last card)
1105 surrender (q) -> surrender (give up :( )""")
1106
1107
1108class FancyView(GameView):
1109 """Fancy view."""
1110
1111 class CardTemplate:
1112 """Card templates."""
1113
1114 template_width = 7
1115 templates = dict()
1116 templates['AS'] = r""" _____
1117|A . |
1118| /.\ |
1119|(_._)|
1120| | |
1121|____V|"""
1122 templates['AD'] = r""" ____
1123|A ^ |
1124| / \ |
1125| \ / |
1126| . |
1127|____V|"""
1128 templates['AC'] = """ ____
1129|A _ |
1130| ( ) |
1131|(_'_)|
1132| | |
1133|____V|"""
1134 templates['AH'] = r""" _____
1135|A_ _ |
1136|( v )|
1137| \ /
1138
1139Марк Бессонов, сегодня в 14:26
1140|
1141| . |
1142|____V|"""
1143 templates['2'] = """ _____
1144|2 |
1145| ^ |
1146| |
1147| ^ |
1148|____Z|"""
1149 templates['3'] = """ _____
1150|3 |
1151| ^ ^ |
1152| |
1153| ^ |
1154|____E|"""
1155 templates['4'] = """ _____
1156|4 |
1157| ^ ^ |
1158| |
1159| ^ ^ |
1160|____h|"""
1161 templates['5'] = """ _____
1162|5 |
1163| ^ ^ |
1164| ^ |
1165| ^ ^ |
1166|____S|"""
1167 templates['6'] = """ _____
1168|6 |
1169| ^ ^ |
1170| ^ ^ |
1171| ^ ^ |
1172|____9|"""
1173 templates['7'] = """ _____
1174|7 |
1175| ^ ^ |
1176|^ ^ ^|
1177| ^ ^ |
1178|____L|"""
1179 templates['8'] = """ _____
1180|8 |
1181|^ ^ ^|
1182| ^ ^ |
1183|^ ^ ^|
1184|____8|"""
1185 templates['9'] = """ _____
1186|9 |
1187|^ ^ ^|
1188|^ ^ ^|
1189|^ ^ ^|
1190|____6|"""
1191 templates['0'] = """ _____
1192|10 ^ |
1193|^ ^ ^|
1194|^ ^ ^|
1195|^ ^ ^|
1196|___0I|"""
1197 templates['JS'] = """ _____
1198|J ww|
1199| ^ {)|
1200|(.)% |
1201| | % |
1202|__%%[|"""
1203 templates['QS'] = """ _____
1204|Q ww|
1205| ^ {(|
1206|(.)%%|
1207| |%%%|
1208|_%%%O|"""
1209 templates['KS'] = """ _____
1210|K WW|
1211| ^ {)|
1212|(.)%%|
1213| |%%%|
1214|_%%%>|"""
1215 templates['JC'] = """ _____
1216|J ww|
1217| o {)|
1218|o o% |
1219| | % |
1220|__%%[|"""
1221 templates['QC'] = """ _____
1222|Q ww|
1223| o {(|
1224|o o%%|
1225| |%%%|
1226|_%%%O|"""
1227 templates['KC'] = """ _____
1228|K WW|
1229| o {)|
1230|o o%%|
1231| |%%%|
1232|_%%%>|"""
1233 templates['JH'] = """ _____
1234|J ww|
1235| {)|
1236|(v)% |
1237| v % |
1238|__%%[|"""
1239 templates['QH'] = """ _____
1240|Q ww|
1241| {(|
1242|(v)%%|
1243| v%%%|
1244|_%%%O|"""
1245 templates['KH'] = """ _____
1246|K WW|
1247| {)|
1248|(v)%%|
1249| v%%%|
1250|_%%%>|"""
1251 templates['JD'] = r""" _____
1252|J ww|
1253| /\{)|
1254| \/% |
1255| % |
1256|__%%[|"""
1257 templates['QD'] = r""" _____
1258|Q ww|
1259| /\{(|
1260| \/%%|
1261| %%%|
1262|_%%%O|"""
1263 templates['KD'] = r""" _____
1264|K WW|
1265| /\{)|
1266| \/%%|
1267| %%%|
1268|_%%%>|"""
1269 templates['??'] = """ _____
1270|? |
1271| |
1272| |
1273| |
1274|____¿|"""
1275
1276 def ask_move(self) -> Move:
1277 """Ask move."""
1278 while True:
1279 try:
1280 command = input(f"{Color.Fg.cyan}Choose your next move! "
1281 + f"{Color.Fg.green} (Use {Color.Fg.light_blue}'help' "
1282 + f"{Color.Fg.green}for help) "
1283 + f"{Color.Fg.orange}> {Color.reset}")
1284 if command not in ['help']:
1285 action = Move.from_str(command)
1286 return action
1287 else:
1288 self.show_help()
1289 except ValueError:
1290 print(f"{Color.Fg.red}Invalid command! {Color.Fg.light_blue}Use 'help' for help {Color.reset}")
1291
1292 def ask_decks_count(self) -> int:
1293 """Ask decks count."""
1294 while True:
1295 count = input(f"{Color.Fg.light_blue}Please enter decks count: {Color.reset}")
1296 if count.isdigit() and 0 < int(count) <= 8:
1297 return int(count)
1298 else:
1299 print(f"{Color.Fg.red}Value must be numeric and between 1-8! {Color.reset}")
1300
1301 def ask_players_count(self) -> int:
1302 """Ask players count."""
1303 while True:
1304 count = input(f"{Color.Fg.cyan}Please enter human players count: {Color.reset}")
1305 if count.isdigit():
1306 return int(count)
1307 else:
1308 print(f"{Color.Fg.red}Value must be numeric! {Color.reset}")
1309
1310 def ask_bots_count(self) -> int:
1311 """Ask bots count."""
1312 while True:
1313 count = input(f"{Color.Fg.light_cyan}Please enter bots count: {Color.reset}")
1314 if count.isdigit():
1315 return int(count)
1316 else:
1317 print(f"{Color.Fg.red}Value must be numeric!{Color.reset}")
1318
1319 def ask_name(self, player_nr: int) -> str:
1320 """Ask player to pick name."""
1321 color = Color.Fg.orange if player_nr % 2 == 0 else Color.Fg.yellow
1322 return input(f"{color}Enter name for player {player_nr}: {Color.Fg.orange}")
1323
1324 def show_table(self, players: list, house, current_hand) -> None:
1325 """Print table."""
1326 ascii_suits = {'S': '♠', 'H': '♥', 'C': '♣', 'D': '♦'}
1327 print(Color.Fg.orange + '-' * 20 * len(players))
1328 print(f"{Color.Fg.light_green}House:{Color.reset}")
1329 card_templates = []
1330 for c in house.cards:
1331 if str(c) in self.CardTemplate.templates.keys():
1332 card_templates.append(self.CardTemplate.templates[str(c)].split('\n'))
1333 else:
1334 card_templates.append(
1335 self.CardTemplate.templates[str(c)[0]].replace('^', ascii_suits[str(c)[-1]]).split('\n'))
1336
1337 print(Color.Fg.light_red, end='')
1338 for l in zip(*card_templates):
1339 print('\t'.join(l))
1340
1341 print(Color.Fg.orange + '-' * 20 * len(players))
1342 print(f"{Color.Fg.light_green}Players:{Color.reset}")
1343
1344 player_templates = []
1345 hand_lengths = []
1346 self.prepare_players(ascii_suits, current_hand, hand_lengths,
1347[Ссылка]
1348404 Not Found
1349http://self.show
1350
1351Марк Бессонов, сегодня в 14:26
1352player_templates, players)
1353
1354 total_width = 0
1355 for i, p in enumerate(players):
1356 width = len(p.hands) * self.CardTemplate.template_width + (len(p.hands) - 1) * 5
1357 total_width += width if total_width == 0 else width + 5
1358 name = p.name if len(p.name) < width else p.name[:width]
1359 color = Color.Fg.purple if current_hand in p.hands else Color.Fg.cyan
1360 print(f"{color}{name:^{width}}", end='')
1361 print(f"\t{Color.Fg.orange}#\t" if i < len(players) - 1 else '', end='')
1362
1363 print('\n' + Color.Fg.orange + '-' * total_width + Color.reset)
1364 for l in zip(*player_templates):
1365 print(f"\t{Color.Fg.orange}#{Color.reset}\t".join(l))
1366 print(Color.Fg.orange + '-' * total_width + Color.reset)
1367
1368 for i, p in enumerate(players):
1369 width = len(p.hands) * self.CardTemplate.template_width + (len(p.hands) - 1) * 5
1370 color = Color.Fg.purple if current_hand in p.hands else Color.Fg.cyan
1371 print(f"{color}{str(p.coins) + '$': ^{width}}", end='')
1372 print(f"\t{Color.Fg.orange}#\t" if i < len(players) - 1 else '', end='')
1373 print(Color.reset)
1374
1375 def prepare_players(self, ascii_suits, current_hand, hand_lengths, player_templates, players):
1376 """Prepare players for printing."""
1377 for p in players:
1378 for h in p.hands:
1379 hand_lengths.append(len(h.cards))
1380 hand_length = max(hand_lengths) * 8
1381 for p in players:
1382 hand_templates = []
1383 for h in p.hands:
1384 hand_color = Color.Fg.pink if h == current_hand else Color.Fg.light_red
1385 cards = ''
1386 for c in h.cards:
1387 cards += '\n' if cards != '' else ''
1388 if str(c) in self.CardTemplate.templates.keys():
1389 cards += self.CardTemplate.templates[str(c)]
1390 else:
1391 cards += self.CardTemplate.templates[str(c)[0]].replace('^', ascii_suits[str(c)[-1]])
1392 for _ in range(hand_length - len(h.cards) * 8):
1393 cards += '\n' + ' ' * self.CardTemplate.template_width
1394 hand_templates.append([hand_color + c for c in cards.split('\n')])
1395
1396 player = ''
1397 for l in zip(*hand_templates):
1398 player += f'\t{Color.Fg.light_green}x{Color.reset}\t'.join(l) + '\n'
1399 player_templates.append(player.rstrip().split('\n'))
1400
1401 def show_help(self):
1402 """Show help."""
1403 print(f"""
1404 {Color.Fg.light_blue}help {Color.Fg.orange}-> """
1405 + f""""{Color.Fg.green}help {Color.Fg.light_green}(print help/commands to console)
1406 {Color.Fg.light_blue}hit {Color.Fg.pink}(h) {Color.Fg.orange}-> """
1407 + f""""{Color.Fg.green}hit {Color.Fg.light_green}(get one more card)
1408 {Color.Fg.light_blue}stand {Color.Fg.pink}(s) {Color.Fg.orange}-> """
1409 + f"""{Color.Fg.green}stand {Color.Fg.light_green}(stop getting more cards, give turn to next player)
1410 {Color.Fg.light_blue}split {Color.Fg.pink}(x) {Color.Fg.orange}-> """
1411 + f"""{Color.Fg.green}split cards {Color.Fg.light_green}(if you have 2 cards with same value you can """
1412 + f"""split them to 2 different decks)
1413 {Color.Fg.light_blue}double {Color.Fg.pink}(d) {Color.Fg.orange}-> """
1414 + f"""{Color.Fg.green}double down {Color.Fg.light_green}(double your bet and receive 1 last card)
1415 {Color.Fg.light_blue}surrender {Color.Fg.pink}(q) {Color.Fg.orange}-> """
1416 + f"""{Color.Fg.light_green}surrender {Color.Fg.light_green}(give up :( ){Color.reset}""")
1417
1418Марк Бессонов, сегодня в 14:26
1419Mall
1420def swap_items(dic: dict) -> dict:
1421 """
1422 Given a dictionary return a new dictionary where keys and values are swapped.
1423 If duplicate keys in the new dictionary exist, leave the first one.
1424
1425 {"a": 1, "b": 2, "c": 3} => {1: "a", 2: "b", 3: "c"}
1426 {"Morning": "Good", "Evening": "Good"} => {"Good": "Morning"}
1427
1428 :param dic: original dictionary
1429 :return: dictionary where keys and values are swapped
1430 """
1431 pass
1432
1433
1434def find_divisors(number) -> list:
1435 """
1436 The task is to find all the divisors for given number in range to the given number's value.
1437 Divisor - a number that divides evenly into another number.
1438 Return list of given number divisors in ascending order.
1439 NB! Numbers 1 and number itself must be excluded if there are more divisors
1440 than 1 and number itself!
1441 (138) > [2, 3, 6, 23, 46, 69]
1442 (3) > [1, 3]
1443 :param number: int
1444 :return: list of number divisors
1445 """
1446 pass
1447
1448def sum_of_multiplies(first_num, second_num, limit) -> int:
1449 """
1450 The task is to find all the multiplies of each given of two numbers within the limit.
1451 Then, find the sum of those multiplies.
1452 (3, 5, 20) => 98 (3 + 6 + 9 + 12 + 15 + 18 + 5 + 10 + 20) 15 is included only once
1453 (3, 3, 10) => 18 (3 + 6 + 9)
1454 (3, 10, 2) => 0
1455 :param first_num: first number
1456 :param second_num: second number
1457 :param limit: limit
1458 :return: sum of multiplies
1459 """
1460 pass
1461
1462def count_odds_and_evens(numbers: list) -> str:
1463 r"""
1464 The task is to count how many odd and even numbers does the given list contain.
1465 Do not count zeros (0).
1466 Result should be displayed as string "ODDS: {number of odds}\nEVENS: {number of evens}"
1467
1468 count_odds_and_events([1, 2, 3]) => "ODDS: 2\nEVENS: 1"
1469 count_odds_and_events([1, 0]) => "ODDS: 1\nEVENS: 0"
1470
1471 :param numbers: list
1472 :return: str
1473 """
1474 pass
1475
1476def sum_between_25(numbers: list) -> int:
1477 """
1478 Return the sum of the numbers in the array which are between 2 and 5.
1479
1480 Summing starts from 2 (not included) and ends at 5 (not included).
1481 The section can contain 2 (but cannot 5 as this would end it).
1482 There can be several sections to be summed.
1483
1484 sum_between_25([1, 3, 6, 7]) => 0
1485 sum_between_25([1, 2, 3, 4, 5, 6]) => 7
1486 sum_between_25([1, 2, 3, 4, 6, 6]) => 19
1487 sum_between_25([1, 3, 3, 4, 5, 6]) => 0
1488 sum_between_25([1, 2, 3, 4, 5, 6, 1, 2, 9, 5, 6]) => 16
1489 sum_between_25([1, 2, 3, 2, 5, 5, 3, 5]) => 5
1490 """
1491 pass
1492
1493
1494def transcribe(dna_strand: str):
1495 """
1496 Write a function that returns a transcribed RNA strand from the given DNA strand,
1497 that is formed by replacing each nucleotide(character) with its complement: G => C, C => G, T => A, A => U
1498 Return None if it is not possible to transcribe a DNA strand.
1499 Empty string should return empty string.
1500
1501 "ACGTGGTCTTAA" => "UGCACCAGAAUU"
1502 "gcu" => None
1503 "a" => "U"
1504
1505 :param dna_strand: original DNA strand
1506 :return: transcribed RNA strand in the uppercase or None
1507 """
1508 pass
1509
1510def union_of_dict(d1: dict, d2: dict):
1511 """
1512 Given two dictionaries return dictionary that has all the key-value pairs that are the same in given dictionaries.
1513
1514 union_of_dict({"a": 1, "b": 2, "c":3}, {"a": 1, "b": 42}) ==> {"a": 1}
1515 union_of_dict({}, {"bar": "foo"}) => {}
1516 """
1517 pass
1518
1519def reserve_list(input_strings: list) -> list:
1520 """
1521 Given list of strings, return new reversed list where each list element is
1522 reversed too. Do not reverse strings followed after element "python". If element is "java" -
1523 reverse mode is on again.
1524 P.S - "python" and "java" are not being reversed
1525
1526 ['apple', 'banana', 'onion'] -> ['noino', 'ananab', 'elppa']
1527 ['lollipop', 'python', 'candy'] -> ['candy', 'python', 'popillol']
1528 ['sky', 'python', 'candy', 'java', 'fly'] -> ['ylf', 'java', 'candy', 'python', 'yks']
1529 ['sky', 'python', 'java', 'candy'] -> ['ydnac', 'java', 'python', 'yks']
1530
1531 :param input_strings: list of strings
1532 :return: reversed list
1533 """
1534 pass
1535
1536def convert_binary_to_decimal(binary_list: list):
1537 """
1538 Extract binary codes of given length from list and convert to decimal numbers.
1539
1540 [0, 0, 0, 0] => 0.
1541 [0, 1, 0, 0] => 4.
1542
1543 :param
1544
1545Марк Бессонов, сегодня в 14:26
1546binary_list: list of 1 and 0 (binary code)
1547 :return: number converted into decimal system
1548 """
1549 pass
1550
1551def print_pages(pages: str) -> list:
1552 """
1553 Find pages to print in console.
1554
1555 examples:
1556 print_pages("2,4,9") -> [2, 4, 9]
1557 print_pages("2,4-7") -> [2, 4, 5, 6, 7]
1558 print_pages("2-5,7,10-12,17") -> [2, 3, 4, 5, 7, 10, 11, 12, 17]
1559 print_pages("1,1") -> [1]
1560 print_pages("") -> []
1561 print_pages("2,1") -> [1, 2]
1562
1563 :param pages: string containing page numbers and page ranges to print.
1564 :return: list of pages to print with no duplicates, sorted in increasing order.
1565 """
1566 pass
1567Lisa
1568Järgmiseid ülesandeid testitakse, aga punkte ei anna.
1569
1570"""Exam 4."""
1571
1572
1573def sum_time(time1: tuple, time2: tuple) -> tuple:
1574 """
1575 Add two times represented as tuples.
1576
1577 #01
1578
1579 Both arguments represent time in format (hours, minutes).
1580 A tuple with two integers. The input is always correct (you don't have to check that).
1581 0 <= hours <= 23
1582 0 <= minutes <= 59
1583
1584 sum_time((0, 10), (0, 20)) => (0, 30)
1585 sum_time((12, 30), (0, 40)) => (13, 10)
1586 sum_time((23, 20), (2, 40)) => (2, 0)
1587
1588 :param time1: tuple with two integers: hours, minutes
1589 :param time2: tuple with two integers: hours, minutes
1590 :return: sum of time1, time2; tuple with two integers: hours, minutes
1591 """
1592 pass
1593
1594
1595def double_char(original_string: str) -> str:
1596 """
1597 Given a string, return a string where for every char in the original is doubled.
1598
1599 #02
1600
1601 double_char("a") => "aa"
1602 double_char("ab") => "aabb"
1603 double_char("") => ""
1604
1605 :param str: string
1606 :return: string where chars are doubled
1607 """
1608 pass
1609
1610
1611def common_elements(list_a: list, list_b: list) -> list:
1612 """
1613 Given two lists, return a list of elements that can be found in both input lists.
1614
1615 #03
1616
1617 The elements can be in any order. The result should have no duplicates.
1618
1619 common_elements([1, 2], [2, 1]) => [1, 2]
1620 common_elements([1, 2], [2, 2, 2]) => [2]
1621 common_elements([1, 2], []) => []
1622 common_elements([1, 2, 3], [3, 4, 5, 3]) => [3]
1623 :param list_a: list
1624 :param list_b: list
1625 :return: list of elements found in list_a and list_b
1626 """
1627 pass
1628
1629
1630def reverse_list(input_strings: list) -> list:
1631 """
1632 Reverse the list and elements except for "python" and "java" and everything between.
1633
1634 #04
1635
1636 Given list of strings, return new reversed list where each list element is
1637 reversed too. Do not reverse strings followed after element "python". If element is "java" -
1638 reverse mode is on again.
1639 P.S - "python" and "java" are not being reversed
1640
1641 reverse_list(['apple', 'banana', 'onion']) -> ['noino', 'ananab', 'elppa']
1642 reverse_list(['lollipop', 'python', 'candy']) -> ['candy', 'python', 'popillol']
1643 reverse_list(['sky', 'python', 'candy', 'java', 'fly']) -> ['ylf', 'java', 'candy', 'python', 'yks']
1644 reverse_list(['sky', 'python', 'java', 'candy']) -> ['ydnac', 'java', 'python', 'yks']
1645
1646 :param input_strings: list of strings
1647 :return: reversed list
1648 """
1649 pass
1650
1651
1652def multiple_elements(items: list) -> dict:
1653 """
1654 Given a list of items (strings), return a dict where key is item (string) and value is count.
1655
1656 #05
1657
1658 But you are interested only in items which are present more than once.
1659 So, items with count 1 should not be in the result.
1660
1661 multiple_items(['a', 'b', 'a']) => {'a': 2}
1662 multiple_items(['a', 'b', 'c']) => {}
1663 multiple_items(['a', 'a', 'c', 'c']) => {'a': 2, 'c': 2}
1664
1665 :param items:
1666 :return:
1667 """
1668 pass
1669
1670
1671def robot_movement(orders):
1672 """
1673 Given a string with robot orders, return the end position and the number of orders executed.
1674
1675 #06
1676
1677 The robot knows the following orders:
1678 - L - turn 90 degrees left
1679 - R - turn 90 degrees right
1680 - D - drive 1 step
1681
1682 There are other orders in the string, but you should ignore those for this exercise.
1683 In front of an order, there can be a multiplier which indicates how many times the following order is executed.
1684 For example:
1685 3D - drives 3 steps
1686 3L - turns 3 times 90 degree left (when starting heading north, it will then be heading east)
1687 123D - drives 123 steps
1688 A - ignore this
1689
1690Марк Бессонов, сегодня в 14:26
1691order
1692 5A - still ignore (both 5 and A)
1693 5AD - is the same as just "D"
1694
1695 The robot starts at (0, 0) heading north. The result should be a tuple in format: (x, y, number of orders executed).
1696 x grows from west to east, y grows from south to north.
1697
1698 Examples:
1699
1700 robot_movement("DDDRDD") => (2, 3, 6)
1701 robot_movement("RRRLLLL") => (0, 0, 7)
1702 robot_movement("RRR7L") => (0, 0, 10)
1703 robot_movement("7A7BD") => (0, 1, 1)
1704
1705 :param orders:
1706 :return:
1707 """
1708 pass
1709
1710
1711def sum_digits(num: int) -> int:
1712 """
1713 Return sum of digits recursively.
1714
1715 #09
1716
1717 Given a positive number as an integer find and return the sum of digits of the number recursively.
1718 This function CANNOT contain any while/for loops.
1719
1720 sum_digits(123) => 6
1721 sum_digits(19) => 10
1722
1723 :param num: number (int)
1724 :return: sum of number's digits
1725 """
1726 pass
1727
1728
1729# 07. University imitation
1730
1731
1732class Book:
1733 """
1734 Represent book model.
1735
1736 When printing the book object, it should show the name.
1737 """
1738
1739 def __init__(self, name: str):
1740 """
1741 Class constructor. Each book has name.
1742
1743 :param name: book name
1744 """
1745 pass
1746
1747
1748class Student:
1749 """
1750 Represent student model.
1751
1752 When printing the student object, it should be as: "name(gpa):[book1, book2]"
1753 ( f"{name}({gpa}):{books}" ).
1754 """
1755
1756 def __init__(self, name: str, gpa: float):
1757 """
1758 Class constructor.
1759
1760 Each student has name and gpa (Grade Point Average)
1761 Student also should have a list of books.
1762
1763 :param name: student's name
1764 :param gpa: student's gpa
1765 """
1766 pass
1767
1768 def add_book(self, book: Book):
1769 """
1770 Add book to student's bag.
1771
1772 :param book: Book
1773 Function does not return anything
1774 """
1775 pass
1776
1777 def can_add_book(self, book: Book):
1778 """
1779 Check if given book can be added to student's bag.
1780 The book can be added if it is not already in student's bag.
1781
1782 :param book: Book
1783 :return: bool
1784 """
1785 pass
1786
1787 def get_books(self):
1788 """
1789 Return a list of all the books.
1790
1791 :return: list of Book objects
1792 """
1793 pass
1794
1795
1796class University:
1797 """
1798 Represent university model.
1799
1800 When printing the object, it should be shown as: "name:[student1, student2]"
1801 ( f"{name}:{students}" ) .
1802 """
1803
1804 def __init__(self, name: str, gpa_required: float, books_required: int):
1805 """
1806 Class constructor.
1807
1808 Each university has name, gpa_required and books_required. Last two
1809 are used to define if student can be added to university.
1810
1811 University should also have a database to keep track of all students.
1812
1813 :param name: university name
1814 :param gpa_required: university required gpa
1815 :param books_required: university required books amount
1816 """
1817 pass
1818
1819 def enrol_student(self, student: Student):
1820 """
1821 Enrol new student to university.
1822
1823 :param student: Student
1824 Function does not return anything
1825 """
1826 pass
1827
1828 def can_enrol_student(self, student: Student):
1829 """
1830 Check if student can be enrolled to university.
1831
1832 Student can be successfully enrolled if:
1833 * he/she has required gpa
1834 * he/she has enough amount of books required
1835 * he/she is not already enrolled to this university
1836
1837 :return: bool
1838 """
1839 pass
1840
1841 def unenrol_student(self, student: Student):
1842 """
1843 Unenrol student from University.
1844
1845 Student can be unenrolled if he/she actually studies in this university.
1846 Function does not return anything
1847 """
1848 pass
1849
1850 def get_students(self):
1851 """
1852 Return a list of all students in current university.
1853
1854 :return: list of Student objects
1855 """
1856 pass
1857
1858 def get_student_highest_gpa(self):
1859 """
1860 Return a list of students (student) with the highest gpa.
1861
1862 :return: list of Student objects
1863 """
1864 pass
1865
1866 def get_student_max_books(self):
1867 """
1868 Return a list of students (student) with the greatest books amount.
1869
1870 :return: list of Student objects
1871 """
1872 pass
1873
1874
1875# 08. Troll Hunt
1876
1877
1878class Troll:
1879 """Troll."""
1880
1881 def __init__(self, name, weight, height, health_points, stamina_points):
1882 """
1883 Constructor.
1884
1885 :param name: troll name.
1886 :param weight: troll weight (t).
1887 :param height: troll height (m).
1888 :param health_points: troll health points (hp).
1889 :param
1890
1891Марк Бессонов, сегодня в 14:26
1892stamina_points: troll stamina points (sp).
1893 """
1894 pass
1895
1896 def get_troll_attack_speed(self):
1897 """
1898 Get the troll attack speed (1-100), integer.
1899
1900 The heavier and higher the troll is, the slower it moves.
1901 The troll speed is calculated using the following formula: 100 / (weight + height).
1902 Round down.
1903 Assume that sum of weight and height is always non-negative and smaller or equal to 100.
1904
1905 EXAMPLE
1906 —----------------------------------------—
1907 troll weight = 3
1908 troll height = 20
1909 then troll speed = 100 / (3 + 20) = 4.347 ~ 4. So the answer is 4.
1910 —----------------------------------------—
1911
1912 :return: troll attack speed, integer.
1913 """
1914 pass
1915
1916 def get_troll_attack_power(self):
1917 """
1918 Get the troll attack power, integer.
1919
1920 The heavier and higher the troll is, the stronger it is.
1921 The troll attack power is just the sum of its weight and height.
1922
1923 EXAMPLE
1924 —----------------------------------------—
1925 troll weight = 5
1926 troll height = 20
1927 then troll attack power = 5 + 20 = 25
1928 —----------------------------------------—
1929
1930 :return: troll attack power, integer.
1931 """
1932 pass
1933
1934 def get_troll_level(self):
1935 """
1936 Get the level of the troll (1-5), integer.
1937
1938 Each troll has a level, which indicates how dangerous it is in combat.
1939 The troll level mostly depends on its hp, sp, speed and attack power.
1940 The level of the troll is calculated using the following formula:
1941
1942 delta = (5 - 1) / (3000 - 500) = 0.0016
1943 troll_power = (troll health points + troll stamina points + troll attack speed + troll attack power)
1944
1945 formula: 0.0016 * (troll_power - 3000) + 5, round down
1946
1947 EXAMPLE
1948 —----------------------------------------—
1949 troll hp = 500
1950 troll stamina = 300
1951 troll atk speed = 4
1952 troll atk power = 25
1953
1954 delta = 0.0016
1955 troll power = (500 + 300 + 4 + 25) = 829
1956
1957 troll lvl = 0.0016 * (829 - 3000) + 5) = 1.53 ~= 1
1958 —----------------------------------------—
1959
1960 :return: troll lvl.
1961 """
1962 pass
1963
1964 def get_name(self):
1965 """
1966 Getter.
1967
1968 :return: troll name.
1969 """
1970 pass
1971
1972 def get_weight(self):
1973 """
1974 Getter.
1975
1976 :return: troll weight.
1977 """
1978 pass
1979
1980 def get_height(self):
1981 """
1982 Getter.
1983
1984 :return: troll height.
1985 """
1986 pass
1987
1988 def get_hp(self):
1989 """
1990 Get health points.
1991
1992 :return: troll hp.
1993 """
1994 pass
1995
1996 def get_sp(self):
1997 """
1998 Get stamina.
1999
2000 :return: troll sp.
2001 """
2002 pass
2003
2004 # add required method(s) to get string representation: f"Name: {troll name}, lvl: {troll lvl}"
2005
2006
2007class Hunter:
2008 """Troll hunter."""
2009
2010 def __init__(self, attack_power, intelligent:bool=False):
2011 """
2012 Constructor.
2013
2014 :param attack_power: Attack power of the hunter.
2015 :param intelligent: Says for itself.
2016 """
2017 pass
2018
2019 def call_for_help(self):
2020 """
2021 If the hunter is intelligent, he can call for help.
2022
2023 Calling for help increases attack power by 10.
2024 :return:
2025 """
2026 pass
2027
2028 def get_attack_power(self):
2029 """
2030 Getter.
2031
2032 :return: hunter's atk power.
2033 """
2034 pass
2035
2036 def is_intelligent(self):
2037 """
2038 Getter.
2039
2040 :return: is hunter intelligent? Boolean.
2041 """
2042 pass
2043
2044
2045class Mission:
2046 """Mission."""
2047
2048 def __init__(self, hunters, troll):
2049 """
2050 Constructor.
2051
2052 :param hunters: list of hunters obj
2053 :param troll: troll obj
2054 """
2055 pass
2056
2057 def hunt(self):
2058 """
2059 The hunters try to slay down the given troll.
2060
2061 The hunters succeed if their total attack power is bigger than troll lvl * 300. The troll will become None.
2062 If their total attack power is smaller than troll lvl * 300, troll kills the most powerful hunter and
2063 all intelligent hunters call for help.
2064 If after calling for help total attack power of hunters is still too low, hunters die and the mission is failed.
2065
2066 If hunters succeed to kill the troll, return true. In other case return false.
2067
2068 :return: boolean
2069 """
2070 pass
2071
2072 def set_hunters(self, hunters):
2073 """
2074 Setter.
2075
2076 :param hunters: list of hunters obj
2077 """
2078 pass
2079
2080 def set_troll(self, troll):
2081 """
2082 Setter.
2083
2084 Check if troll is Troll class obj and set. In other case do not do anything.
2085
2086 :param troll: Troll class obj
2087 """
2088 pass
2089
2090 def
2091
2092Марк Бессонов, сегодня в 14:26
2093get_troll(self):
2094 """
2095 Getter.
2096
2097 :return: troll
2098 """
2099 pass
2100
2101
2102if __name__ == '__main__':
2103 # University examples
2104 ttu = University('ttu', 60.0, 1)
2105 print(ttu) # ttu:[]
2106 assert str(ttu) == "ttu:[]"
2107
2108 betty = Student('Betty', 61.0)
2109 print(betty) # Betty(61.0):[]
2110 assert str(betty) == "Betty(61.0):[]"
2111
2112 print(ttu.can_enrol_student(betty)) # False -> Betty has not enough of books required
2113 assert not ttu.can_enrol_student(betty)
2114 print(betty.get_books()) # []
2115 assert betty.get_books() == []
2116
2117 math = Book('math')
2118 print(math) # math
2119 assert str(math) == "math"
2120 betty.add_book(math)
2121 print(ttu.can_enrol_student(betty)) # True -> now Betty has enough of books required
2122 assert ttu.can_enrol_student(betty)
2123 ttu.enrol_student(betty)
2124
2125 print(ttu) # ttu:[Betty(61.0):[math]]
2126 assert str(ttu) == "ttu:[Betty(61.0):[math]]"
2127 print(betty.can_add_book(math)) # False -> Already has this book
2128 assert not betty.can_add_book(math)
2129
2130 economics = Book('economics')
2131 betty.add_book(economics)
2132 print(betty.get_books()) # [math, economics]
2133 assert str(betty.get_books()) == "[math, economics]"
2134
2135 steven = Student('Steven', 59.0)
2136 print(ttu.can_enrol_student(steven)) # False -> Not enough high gpa
2137 assert not ttu.can_enrol_student(steven)
2138
2139 students = [Student('Sally', 62.0), Student('Ben', 74.6), Student('Ben', 96.1)]
2140
2141 for student in students:
2142 student.add_book(math)
2143 ttu.enrol_student(student)
2144
2145 print(ttu.students) # [Betty(61.0):[math, economics], Sally(62.0):[math], Ben(74.6):[math], Ben(96.1):[math]]
2146 assert str(ttu.students) == "[Betty(61.0):[math, economics], Sally(62.0):[math], Ben(74.6):[math], Ben(96.1):[math]]"
2147 print(ttu.get_student_highest_gpa()) # [Ben(96.1):[math]]
2148 assert str(ttu.get_student_highest_gpa()) == "[Ben(96.1):[math]]"
2149 print(ttu.get_student_max_books()) # [Betty(61.0):[math, economics]]
2150 assert str(ttu.get_student_max_books()) == "[Betty(61.0):[math, economics]]"
2151
2152 collin = Student('Collin', 96.1)
2153 collin.add_book(math)
2154 collin.add_book(economics)
2155 ttu.enrol_student(collin)
2156
2157 print(ttu.get_student_highest_gpa()) # [Ben(96.1):[math], Collin(96.1):[math, economics]]
2158 assert str(ttu.get_student_highest_gpa()) == "[Ben(96.1):[math], Collin(96.1):[math, economics]]"
2159 print(ttu.get_student_max_books()) # [Betty(61.0):[math, economics], Collin(96.1):[math, economics]]
2160 assert str(ttu.get_student_max_books()) == "[Betty(61.0):[math, economics], Collin(96.1):[math, economics]]"
2161
2162 print("Good job! University done!") # <- if you reach here, then all example asserts work, good job!
2163
2164 # Troll hunt
2165 t1 = Troll("Small Ice troll", 3, 25, 500, 700)
2166 t2 = Troll("Big Ice troll", 10, 40, 2000, 1500)
2167 h = Hunter(100, True)
2168 h1 = Hunter(122)
2169
2170 hunters1 = [Hunter(50), Hunter(30), Hunter(12)]
2171 hunters2 = [Hunter(120), Hunter(99), Hunter(98)]
2172 smart_hunters = [Hunter(0, True) for _ in range(50)]
2173 hunters2 += smart_hunters
2174
2175 m = Mission(hunters=hunters1, troll=t1)
2176
2177 assert t1.get_height() == 25
2178 assert t1.get_weight() == 3
2179 assert t1.get_hp() == 500
2180 assert t1.get_sp() == 700
2181 assert t1.get_name() == "Small Ice troll"
2182
2183 assert t1.get_troll_attack_speed() == 3
2184 assert t1.get_troll_attack_power() == 28
2185 assert t2.get_troll_attack_power() == 50
2186 assert t1.get_troll_level() == 2
2187 assert t2.get_troll_level() == 5
2188
2189 assert str(t1) == "Name: Small Ice troll, lvl: 2"
2190 assert str(t2) == "Name: Big Ice troll, lvl: 5"
2191
2192 assert h.get_attack_power() == 100
2193 h.call_for_help()
2194 assert h.get_attack_power() == 110
2195 h1.call_for_help()
2196 assert h1.get_attack_power() == 122
2197 assert h.is_intelligent()
2198
2199 assert m.get_troll() == t1
2200 assert not m.hunt()
2201
2202 m.set_hunters(hunters2)
2203 assert m.hunt()
2204
2205 m.set_troll(t2)
2206 assert not m.hunt()
2207
2208 print("Good job! Troll hunt works!")
2209[Ссылка]
2210HRAÐLESTRARSKÓLINN - KENNSLUVEFUR
2211http://h.is
2212
2213Марк Бессонов, сегодня в 14:26
2214World
2215Url, kust kõik pokemonid kätte saab: https://pokeapi.co/api/v2/pokemon?offset=0&limit=100000
2216
2217Import json'it kasutades saab viia dictionary json kujule
2218
2219self.data = {"name": str,
2220 "speed": int,
2221 "attack": int,
2222 "defence": int,
2223 "special-attack": int,
2224 "special-defence": int,
2225 "hp": int,
2226 "types": List<str>,
2227 "abilities": List<str>,
2228 "forms": List<str>,
2229 "moves": List<str>,
2230 "height": int,
2231 "base_experience": int}
2232näide ühest pokemonist
2233
2234{"name": "bulbasaur", "speed": 45, "attack": 49, "defense": 49, "special-attack": 65, "special-defense": 65, "hp": 45, "types": ["poison", "grass"], "abilities": ["chlorophyll", "overgrow"], "forms": ["bulbasaur"], "moves": ["razor-wind", "swords-dance", "cut", "bind", "vine-whip", "headbutt", "tackle", "body-slam", "take-down", "double-edge", "growl", "strength", "mega-drain", "leech-seed", "growth", "razor-leaf", "solar-beam", "poison-powder", "sleep-powder", "petal-dance", "string-shot", "toxic", "rage", "mimic", "double-team", "defense-curl", "light-screen", "reflect", "bide", "sludge", "skull-bash", "amnesia", "flash", "rest", "substitute", "snore", "curse", "protect", "sludge-bomb", "mud-slap", "giga-drain", "endure", "charm", "swagger", "fury-cutter", "attract", "sleep-talk", "return", "frustration", "safeguard", "sweet-scent", "synthesis", "hidden-power", "sunny-day", "rock-smash", "facade", "nature-power", "ingrain", "knock-off", "secret-power", "grass-whistle", "bullet-seed", "magical-leaf", "natural-gift", "worry-seed", "seed-bomb", "energy-ball", "leaf-storm", "power-whip", "captivate", "grass-knot", "venoshock", "round", "echoed-voice", "grass-pledge", "work-up", "grassy-terrain", "confide"], "height": 7, "weight": 69, "base_experience": 64}
2235Fighting multipliers
2236 normal fighting flying poison ground rock bug ghost steel fire water grass electric psychic ice dragon dark fairy
2237normal 1.0 1.0 1.0 1.0 1.0 0.5 1.0 0.0 0.5 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0
2238fighting 2.0 1.0 0.5 0.5 1.0 2.0 0.5 0.0 2.0 1.0 1.0 1.0 1.0 0.5 2.0 1.0 2.0 0.5
2239flying 1.0 2.0 1.0 1.0 1.0 0.5 2.0 1.0 0.5 1.0 1.0 2.0 0.5 1.0 1.0 1.0 1.0 1.0
2240poison 1.0 1.0 1.0 0.5 0.5 0.5 1.0 0.5 0.0 1.0 1.0 2.0 1.0 1.0 1.0 1.0 1.0 2.0
2241ground 1.0 1.0 0.0 2.0 1.0 2.0 0.5 1.0 2.0 2.0 1.0 0.5 2.0 1.0 1.0 1.0 1.0 1.0
2242rock 1.0 0.5 2.0 1.0 0.5 1.0 2.0 1.0 0.5 2.0 1.0 1.0 1.0 1.0 2.0 1.0 1.0 1.0
2243bug 1.0 0.5 0.5 0.5 1.0 1.0 1.0 0.5 0.5 0.5 1.0 2.0 1.0 2.0 1.0 1.0 2.0 0.5
2244ghost 0.0 1.0 1.0 1.0 1.0 1.0 1.0 2.0 1.0 1.0 1.0 1.0 1.0 2.0 1.0 1.0 0.5 1.0
2245steel 1.0 1.0 1.0 1.0 1.0 2.0 1.0 1.0 0.5 0.5 0.5 1.0 0.5 1.0 2.0 1.0 1.0 2.0
2246fire 1.0 1.0 1.0 1.0 1.0 0.5 2.0 1.0 2.0 0.5 0.5 2.0 1.0 1.0 2.0 0.5 1.0 1.0
2247water 1.0 1.0 1.0 1.0 2.0 2.0 1.0 1.0 1.0 2.0 0.5 0.5 1.0 1.0 1.0 0.5 1.0 1.0
2248grass 1.0 1.0 0.5 0.5 2.0 2.0 0.5 1.0 0.5 0.5 2.0 0.5 1.0 1.0 1.0 0.5 1.0 1.0
2249electric 1.0 1.0 2.0 1.0 0.0 1.0 1.0 1.0 1.0 1.0 2.0 0.5 0.5 1.0 1.0 0.5 1.0 1.0
2250psychic 1.0 2.0 1.0 2.0 1.0 1.0 1.0 1.0 0.5 1.0 1.0 1.0 1.0 0.5 1.0 1.0 0.0 1.0
2251ice 1.0 1.0 2.0 1.0 2.0 1.0 1.0 1.0 0.5 0.5 0.5 2.0 1.0 1.0 0.5 2.0 1.0 1.0
2252dragon 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 0.5 1.0 1.0 1.0 1.0 1.0 1.0 2.0 1.0 0.0
2253dark 1.0 0.5 1.0 1.0 1.0 1.0 1.0 2.0 1.0 1.0 1.0 1.0 1.0 2.0 1.0 1.0 0.5 0.5
2254fairy 1.0 2.0 1.0 0.5 1.0 1.0 1.0 1.0 0.5 0.5 1.0 1.0 1.0 1.0 1.0 2.0 2.0 1.0
2255PS: Write a quick script to parse it into a matrix :)
2256
2257class World:
2258 """World class."""
2259
2260 def __init__(self, name, offset, limit):
2261 """
2262 Class constructor.
2263 :param name: name of the pokemon world
2264 :param offset: offset for api request
2265 :param limit: limit for api request
2266 Check if f"{name}_{offset}_{limit}.txt" file exists, if it does, read pokemons in from that file, if not, then make an api
2267 request to f"https://pokeapi.co/api/v2/pokemon?offset={offset}&limit={limit}" to get pokemons and dump them to
2268 f"{name}_{offset}_{limit}.txt" file
2269 """
2270 self.pokemons = []
2271
2272 def dump_pokemons_to_file_as_json(self, name):
2273 """
2274 :param name: name of the .txt file
2275 Write all self.pokemons separated by a newline to the given filename(if it doesnt exist, then create one)
2276
2277Марк Бессонов, сегодня в 14:26
2278PS: Write the pokemon.__str__() version, not __repr__() as only name is useless :)
2279 """
2280 pass
2281
2282 def fight(self):
2283 """
2284 A wild brawl between all pokemons where points are assigned to winners
2285 Note, every pokemon fights another pokemon only once
2286 Fight lasts until one pokemon runs out of hp.
2287 every pokemon hits only 1 time per turn and they take turns when they attack.
2288 Call choose_which_pokemon_hits_first(pokemon1, pokemon2): to determine which pokemon hits first
2289 Call pokemon_duel function in this method with the aforementioned pokemons.
2290 every exception thrown by called sub methods must be caught and dealt with.
2291 """
2292 pass
2293
2294 @staticmethod
2295 def pokemon_duel(pokemon1, pokemon2):
2296 """
2297 :param pokemon1: pokemon, who attacks first.
2298 :param pokemon2: pokemon, who attacks second.
2299 :return winner: pokemon, who won.
2300
2301 Here 2 pokemons fight.
2302 To get the attack and defense of the pokemon, call pokemon1.get_pokemon_attack()
2303 and pokemon1.get_pokemon_defense() respectively.
2304 Attack is multiplied by the pokemon1.get_attack_multiplier(list(second.data['types'])) multiplier
2305 Total attack is
2306 pokemon1.get_pokemon_attack(turn_counter) * multiplier1 - second.get_pokemon_defense(turn_counter)
2307 [turn counter starts from 1]
2308 Total attack is subtracted from other pokemons hp.
2309 Pokemons can not heal during the fight. (when total attack is negative, no damage is dealt)
2310 If the fight between 2 pokemons lasts more than 100 turns, then PokemonFightResultsInATieException() is thrown.
2311 If one pokemon runs out of hp, fight ends and the winner gets 1 point, (self.score += 1)
2312 then both pokemons are healed to full hp.
2313 """
2314 @staticmethod
2315 def choose_which_pokemon_hits_first(pokemon1, pokemon2):
2316 """
2317 :param pokemon1:
2318 :param pokemon2:
2319 Pokemon who's speed is higher, goes first. if both pokemons have the same speed, then pokemon who's weight
2320 is lower goes first, if both pokemons have same weight, then pokemon who's height is lower goes first,
2321 if both pokemons have the same height, then the pokemon with more abilities goes first, if they have the same
2322 amount of abilities, then the pokemon with more moves goes first, if the pokemons have the same amount of
2323 moves, then the pokemon with higher base_experience goes first, if the pokemons have the same
2324 base_experience then SamePokemonFightException() is thrown
2325 :return pokemon1 who goes first and pokemon2 who goes second (return pokemon1, pokemon2)
2326 """
2327 pass
2328
2329 def get_leader_board(self):
2330 """
2331 Get Pokemons by given format in a list sorted by the pokemon.score.
2332
2333 In case of the same score, order pokemons by their name (ascending).
2334
2335 :return: List of leader board. where winners are first
2336 """
2337 pass
2338
2339 def get_pokemons_sorted_by_attribute(self, attribute: str):
2340 """
2341 Get Pokemons by given format in a list sorted by the pokemon.data[attribute]
2342 :param attribute: pokemon data attribute to sort by
2343 :return: sorted List of pokemons
2344 """
2345 pass
2346Pokemon
2347class Pokemon:
2348 """Class for Pokemon."""
2349
2350 def __init__(self, url_or_path_name: str):
2351 """
2352 Class constructor.
2353 :param url_or_path_name: url or json object.
2354 If it is url, then parse information from request to proper
2355 json file and save it to self.data.
2356 If it is a string representation of a json object, then parse it into json object and save to self.data
2357 """
2358 self.score = 0
2359 self.data = {}
2360
2361 def parse_json_to_pokemon_information(self, url):
2362 """
2363 :param url: url where the information is requested.
2364 Called from constructor and this method requests data from url to parse it into proper json object
2365 and then saved under self.data example done previously
2366 """
2367 pass
2368
2369 def get_attack_multiplier(self, other: list):
2370 """
2371 self.pokemon is attacking, other is defending
2372 :param other: list of other pokemon2.data['types']
2373 Calculate Pokemons attack multiplier against others types and take the best result.
2374 get the initial multiplier from Fighting Multiplier matrix.
2375 For example if self.type == ['fire'] and other == ['ground']: return fighting_multipliers['fire']['ground']
2376 if
2377
2378Марк Бессонов, сегодня в 14:26
2379the defendant has dual types, then multiply the multipliers together.
2380 if the attacker has dual-types, then the best option is
2381 chosen(attack can only be of 1 type, choose better[higher multiplier])
2382 :return: Multiplier.
2383 """
2384 pass
2385
2386 def get_pokemon_attack(self, turn_counter):
2387 """
2388 :param turn_counter: every third round the attack is empowered. (return self.data['special-attack'])
2389 otherwise basic attack is returned (self.data['attack'])
2390 """
2391 pass
2392
2393 def get_pokemon_defense(self, turn_counter):
2394 """
2395 Note: whatever the result is returned, return half of it instead (for example return self.data['defense'] / 2)
2396 :param turn_counter: every second round the defense is empowered. (return self.data['special-defense'])
2397 otherwise basic defense is returned (self.data['defense'])
2398 """
2399
2400 def __str__(self):
2401 """
2402 String representation of json(self.data) object.
2403 One way to accomplish this is to use json.dumps functionality
2404 :return: string version of json file with necessary information
2405 """
2406 pass
2407
2408 def __repr__(self):
2409 """
2410 Object representation.
2411 :return: Pokemon's name in string format and his score, for example: "garchomp-mega 892"
2412 """
2413 pass
2414Exceptions
2415class SamePokemonFightException(Exception):
2416 """Custom exception thrown when same pokemons are fighting."""
2417 pass
2418
2419
2420class PokemonFightResultsInATieException(Exception):
2421 """Custom exception thrown when the fight lasts longer than 100 rounds."""
2422 pass
2423
2424Марк Бессонов, сегодня в 14:26
2425Mall
2426"""PR15 - anonymous."""
2427
2428
2429class Person:
2430 """Person."""
2431
2432 def __init__(self, first_name: str, surname: str, gender: str, age: int, weight: int, height: int, rating: int):
2433 """Initialize the Person object."""
2434 self.first_name = first_name
2435 self.surname = surname
2436 self.gender = gender
2437 self.age = age
2438 self.weight = weight
2439 self.height = height
2440 self.rating = rating
2441
2442 def increase_rating(self, number: int):
2443 """
2444 Multiply rating by the given number.
2445
2446 :param number: multiplier
2447 :return: rating
2448 """
2449 self.rating *= number
2450 return self.rating
2451
2452 def __repr__(self):
2453 """Person object representation."""
2454 return self.first_name
2455
2456
2457def find_the_tallest_person(person_list: list) -> Person:
2458 """
2459 Find the tallest person. If multiple people are of the same height return the first one on the list.
2460
2461 :param person_list: input list
2462 :return: Person object
2463 """
2464
2465
2466def filter_list_by_gender(person_list: list, gender: str) -> list:
2467 """
2468 Return list of people who identify as gender or whose gender is "Undefined".
2469
2470 :param person_list: input list
2471 :param gender: gender
2472 :return: list of people
2473 """
2474
2475
2476def filter_list_by_age(person_list: list, bottom_age: int, upper_age: int) -> list:
2477 """
2478 Filter out people who are younger than bottom_age and older than upper_age.
2479
2480 :param person_list: input list
2481 :param bottom_age:
2482 :param upper_age:
2483 :return: list of people
2484 """
2485
2486
2487def filter_list_by_bmi(person_list: list) -> list:
2488 """
2489 Get all the people with normal complexion (bmi between 18.5 and 25). BMI = weight(kg)/ height^2(m).
2490
2491 :param person_list: input list
2492 :return: list of people
2493 """
2494
2495
2496def get_the_rating_product(person_list: list) -> int:
2497 """
2498 Return the result of multiplication of all the ratings.
2499
2500 :param person_list: input list
2501 :return: product
2502 """
2503
2504
2505def sort_by_name_length(person_list: list) -> list:
2506 """
2507 Sort list of people by the length of their full name in descending order. Original list must remain unchanged.
2508
2509 :param person_list: input list
2510 :return: sorted list of people
2511 """
2512
2513
2514def get_list_of_increased_ratings(person_list: list, number: int) -> list:
2515 """
2516 Return list of ratings of all people multiplied by the given number.
2517
2518 :param number: multiplier
2519 :param person_list: input list
2520 :return: list of ratings
2521 """
2522
2523
2524def get_people_with_the_lowest_rating(person_list: list) -> list:
2525 """
2526 Return list of people with the lowest rating.
2527 :param person_list: input list
2528 :return: list of people
2529 """
2530
2531
2532if __name__ == "__main__":
2533 chrysa = Person("Chrysa", "Bygraves", "Helicopter", 27, 97, 173, 4)
2534 norbie = Person("Norbie", "Lanyon", "Unicorn", 23, 83, 194, 5)
2535 rand = Person("Rand", "Worcs", "Male", 39, 56, 169, 8)
2536 pavia = Person("Pavia", "Craft", "Unicorn", 22, 64, 181, 2)
2537 tobit = Person("Tobit", "Messom", "Female", 61, 140, 177, 7)
2538 eda = Person("Eda", "Merkle", "Undefined", 23, 55, 176, 2)
2539
2540 list_of_people = [chrysa, norbie, rand, pavia, tobit, eda]
2541 print(find_the_tallest_person(list_of_people)) # Norbie
2542 print(filter_list_by_gender(list_of_people, "Unicorn")) # [Norbie, Pavia, Eda]
2543 print(filter_list_by_age(list_of_people, 18, 35)) # [Chrysa, Norbie, Pavia, Eda]
2544 print(filter_list_by_bmi(list_of_people)) # [Norbie, Rand, Pavia]
2545 print(get_the_rating_product(list_of_people)) # 4480
2546 print(sort_by_name_length(list_of_people)) # [Chrysa, Norbie, Tobit, Pavia, Rand, Eda]
2547 print(get_list_of_increased_ratings(list_of_people, 2)) # [8, 10, 16, 4, 14, 4]
2548 print(get_people_with_the_lowest_rating(list_of_people)) # [Pavia, Eda]