diff options
Diffstat (limited to 'challenge-263/sgreen/python')
| -rwxr-xr-x | challenge-263/sgreen/python/ch-1.py | 23 | ||||
| -rwxr-xr-x | challenge-263/sgreen/python/ch-2.py | 30 | ||||
| -rwxr-xr-x | challenge-263/sgreen/python/test.py | 30 |
3 files changed, 83 insertions, 0 deletions
diff --git a/challenge-263/sgreen/python/ch-1.py b/challenge-263/sgreen/python/ch-1.py new file mode 100755 index 0000000000..5f1e0be8fb --- /dev/null +++ b/challenge-263/sgreen/python/ch-1.py @@ -0,0 +1,23 @@ +#!/usr/bin/env python3 + +import sys + + +def target_index(ints: list, k: int) -> list: + # Sort the array + ints = sorted(ints) + + # Return the indexes where the item is 'k' + return [pos for pos, value in enumerate(ints) if value == k] + + +def main(): + # Convert input into integers + array = [int(n) for n in sys.argv[1:]] + k = array.pop() + result = target_index(array, k) + print('(' + ', '.join(map(str, result)) + ')') + + +if __name__ == '__main__': + main() diff --git a/challenge-263/sgreen/python/ch-2.py b/challenge-263/sgreen/python/ch-2.py new file mode 100755 index 0000000000..a3a6d6a181 --- /dev/null +++ b/challenge-263/sgreen/python/ch-2.py @@ -0,0 +1,30 @@ +#!/usr/bin/env python3 + +from collections import defaultdict +import json +import sys + + +def merge_items(*arrays) -> list: + # Calculate the total of each items + totals = defaultdict(int) + for array in arrays: + for item in array: + item_id, item_qty = item + totals[item_id] += item_qty + + # Turn this into a sorted list of item_id and item_qty pairs + return [[item, totals[item]] for item in sorted(totals)] + + +def main(): + # Convert each input into a list of lists + arrays = [] + for json_str in sys.argv[1:]: + arrays.append(json.loads(json_str)) + result = merge_items(*arrays) + print(json.dumps(result)) + + +if __name__ == '__main__': + main() diff --git a/challenge-263/sgreen/python/test.py b/challenge-263/sgreen/python/test.py new file mode 100755 index 0000000000..46adb6e558 --- /dev/null +++ b/challenge-263/sgreen/python/test.py @@ -0,0 +1,30 @@ +#!/usr/bin/env python3 + +import unittest +ch_1 = __import__('ch-1') +ch_2 = __import__('ch-2') + + +class TestClass(unittest.TestCase): + def test_ch_1(self): + self.assertEqual(ch_1.target_index([1, 5, 3, 2, 4, 2], 2), [1, 2]) + self.assertEqual(ch_1.target_index([1, 2, 4, 3, 5], 6), []) + self.assertEqual(ch_1.target_index([5, 3, 2, 4, 2, 1], 4), [4]) + + def test_ch_2(self): + self.assertEqual( + ch_2.merge_items([[1, 1], [2, 1], [3, 2]], [[2, 2], [1, 3]]), + [[1, 4], [2, 3], [3, 2]] + ) + self.assertEqual( + ch_2.merge_items([[1, 2], [2, 3], [1, 3], [3, 2]], [[3, 1], [1, 3]]), + [[1, 8], [2, 3], [3, 3]] + ) + self.assertEqual( + ch_2.merge_items([[1, 1], [2, 2], [3, 3]], [[2, 3], [2, 4]]), + [[1, 1], [2, 9], [3, 3]] + ) + + +if __name__ == '__main__': + unittest.main() |
