1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
|
### https://theweeklychallenge.org/blog/perl-weekly-challenge-253/
"""
Task 2: Weakest Row
Submitted by: [44]Mohammad S Anwar
__________________________________________________________________
You are given an m x n binary matrix i.e. only 0 and 1 where 1 always
appear before 0.
A row i is weaker than a row j if one of the following is true:
a) The number of 1s in row i is less than the number of 1s in row j.
b) Both rows have the same number of 1 and i < j.
Write a script to return the order of rows from weakest to strongest.
Example 1
Input: $matrix = [
[1, 1, 0, 0, 0],
[1, 1, 1, 1, 0],
[1, 0, 0, 0, 0],
[1, 1, 0, 0, 0],
[1, 1, 1, 1, 1]
]
Output: (2, 0, 3, 1, 4)
The number of 1s in each row is:
- Row 0: 2
- Row 1: 4
- Row 2: 1
- Row 3: 2
- Row 4: 5
Example 2
Input: $matrix = [
[1, 0, 0, 0],
[1, 1, 1, 1],
[1, 0, 0, 0],
[1, 0, 0, 0]
]
Output: (0, 2, 3, 1)
The number of 1s in each row is:
- Row 0: 1
- Row 1: 4
- Row 2: 1
- Row 3: 1
__________________________________________________________________
Last date to submit the solution 23:59 (UK Time) Sunday 28th January
2024.
__________________________________________________________________
SO WHAT DO YOU THINK ?
"""
### solution by pokgopun@gmail.com
def weakestRow(tup: tuple):
r = tuple(e.count(1) for e in tup)
return tuple(
sorted(
range(len(tup)), key=lambda x: r[x]
)
)
import unittest
class TestWeakestRow(unittest.TestCase):
def test(self):
for inpt,otpt in {
(
(1, 1, 0, 0, 0),
(1, 1, 1, 1, 0),
(1, 0, 0, 0, 0),
(1, 1, 0, 0, 0),
(1, 1, 1, 1, 1)
): (2, 0, 3, 1, 4),
(
(1, 0, 0, 0),
(1, 1, 1, 1),
(1, 0, 0, 0),
(1, 0, 0, 0)
): (0, 2, 3, 1),
}.items():
self.assertEqual(weakestRow(inpt),otpt)
unittest.main()
|