diff options
| author | 冯昶 <fengchang@novel-supertv.com> | 2022-10-24 17:44:04 +0800 |
|---|---|---|
| committer | 冯昶 <fengchang@novel-supertv.com> | 2022-10-24 17:44:04 +0800 |
| commit | 7783ecb7dad2ae5ea3d3022a13e3901c196c4154 (patch) | |
| tree | fa408d0b19c541602d81799c8a13eea61df2cb8f /challenge-187/mohammad-anwar/python/ch-2.py | |
| parent | a406c6935f88c7afa04a707a2611ebe4fe4eadae (diff) | |
| parent | bb06570f6b1634ca14bfd08927f3bfc6c052c494 (diff) | |
| download | perlweeklychallenge-club-7783ecb7dad2ae5ea3d3022a13e3901c196c4154.tar.gz perlweeklychallenge-club-7783ecb7dad2ae5ea3d3022a13e3901c196c4154.tar.bz2 perlweeklychallenge-club-7783ecb7dad2ae5ea3d3022a13e3901c196c4154.zip | |
Merge remote-tracking branch 'upstream/master'
Diffstat (limited to 'challenge-187/mohammad-anwar/python/ch-2.py')
| -rw-r--r-- | challenge-187/mohammad-anwar/python/ch-2.py | 61 |
1 files changed, 61 insertions, 0 deletions
diff --git a/challenge-187/mohammad-anwar/python/ch-2.py b/challenge-187/mohammad-anwar/python/ch-2.py new file mode 100644 index 0000000000..7aefb10fe3 --- /dev/null +++ b/challenge-187/mohammad-anwar/python/ch-2.py @@ -0,0 +1,61 @@ +#!/usr/bin/python3 + +''' + +Week 187: + + https://theweeklychallenge.org/blog/perl-weekly-challenge-187 + +Task #2: Magical Triplets + + You are given a list of positive numbers, @n, having at least + 3 numbers. + + Write a script to find the triplets (a, b, c) from the given list + that satisfies the following rules. + + 1. a + b > c + 2. b + c > a + 3. a + c > b + 4. a + b + c is maximum. + + In case, you end up with more than one triplets having the maximum + then pick the triplet where a >= b >= c. + +''' + +import unittest +import itertools + +def magicalTriplets(array): + array.sort() + magical = {} + for triplet in itertools.permutations(array, 3): + triplet_list = list(triplet) + triplet_list.sort(reverse=True) + a = triplet_list[0] + b = triplet_list[1] + c = triplet_list[2] + if (a + b > c) and (b + c > a) and (a + c > b): + key = ':'.join([str(i) for i in triplet_list]) + val = sum(triplet_list) + magical[key] = val + + if len(magical) == 0: + return [] + + magical_triplet = sorted(magical, key=magical.get, reverse=True)[0] + return [int(i) for i in magical_triplet.split(":")] + +# +# +# Unit test class + +class TestMagicalTriplets(unittest.TestCase): + def test_MagicalTriplets(self): + self.assertEqual(magicalTriplets([1, 2, 3, 2]), [3, 2, 2], 'Example 1') + self.assertEqual(magicalTriplets([1, 3, 2]), [], 'Example 2') + self.assertEqual(magicalTriplets([1, 1, 2, 3]), [], 'Example 3') + self.assertEqual(magicalTriplets([2, 4, 3]), [4, 3, 2], 'Example 4') + +unittest.main() |
