Advertisement
fkudinov

11. Majority / Вирішуємо задачі на Python CheckIO Українською

Sep 7th, 2023
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.74 KB | Source Code | 0 0
  1. # ---------    tasks/majority.py --------------
  2.  
  3. def is_majority(items: list) -> bool:
  4.  
  5.     true_count = 0
  6.     false_count = 0
  7.  
  8.     for i in items:
  9.         if i is True:
  10.             true_count += 1
  11.         else:
  12.             false_count += 1
  13.  
  14.     return true_count > false_count
  15.  
  16.  
  17. def is_majority_count(items) -> bool:
  18.     true_count = items.count(True)
  19.     false_count = items.count(False)
  20.     return true_count > false_count
  21.  
  22.  
  23. def is_majority_len(items) -> bool:
  24.     true_count = items.count(True)
  25.     return true_count * 2 > len(items)
  26.  
  27.  
  28. def is_majority_sum(items) -> bool:
  29.     true_count = sum(items)
  30.     return true_count * 2 > len(items)
  31.  
  32.  
  33. def is_majority_agg(items) -> bool:
  34.     return sum([-1, 1][i] for i in items) > 0
  35.  
  36.  
  37. # works for python 3.10+
  38. # def is_majority_match_case(items) -> bool:
  39. #
  40. #     total = 0
  41. #
  42. #     for i in items:
  43. #
  44. #         match i:
  45. #             case True:
  46. #                 res = 1
  47. #             case _:
  48. #                 res = -1
  49. #
  50. #         total += res
  51. #
  52. #     return total > 0
  53.  
  54.  
  55. # -----------  tests/test_majority.py  ----------------
  56.  
  57. import pytest
  58.  
  59. from tasks.majority import (is_majority, is_majority_count, is_majority_len,
  60.                             is_majority_sum, is_majority_agg)
  61.  
  62.  
  63. @pytest.mark.parametrize("func", [
  64.     is_majority,
  65.     is_majority_count,
  66.     is_majority_len,
  67.     is_majority_sum,
  68.     is_majority_agg
  69. ])
  70. @pytest.mark.parametrize(["data", "res"], [
  71.     [[True, True, False, True, False], True],
  72.     [[True, True, False], True],
  73.     [[True, True, False, False], False],
  74.     [[True, True, False, False, False], False],
  75.     [[False], False],
  76.     [[True], True],
  77.     [[], False],
  78. ])
  79. def test_majority(func, data, res):
  80.     assert func(data) == res
  81.  
Tags: checkio
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement