From 8977c2782c87685be94fd43b452978c10f3614f7 Mon Sep 17 00:00:00 2001 From: Steven Date: Mon, 26 Aug 2024 19:56:55 +0100 Subject: add solutions week 284 in python --- challenge-284/steven-wilson/python/ch-1.py | 30 +++++++++++++++++++++++++ challenge-284/steven-wilson/python/ch-2.py | 36 ++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+) create mode 100644 challenge-284/steven-wilson/python/ch-1.py create mode 100644 challenge-284/steven-wilson/python/ch-2.py diff --git a/challenge-284/steven-wilson/python/ch-1.py b/challenge-284/steven-wilson/python/ch-1.py new file mode 100644 index 0000000000..6e38592c6a --- /dev/null +++ b/challenge-284/steven-wilson/python/ch-1.py @@ -0,0 +1,30 @@ +#!/usr/bin/env python3 + +from collections import Counter + + +def lucky_integer(*integers): + """ Given an array of integers, return the lucky integer if found otherwise + return -1. If there are more than one then return the largest. + + A lucky integer is an integer that has a frequency in the array equal + to its value. + + >>> lucky_integer(2, 2, 3, 4) + 2 + >>> lucky_integer(1, 2, 2, 3, 3, 3) + 3 + >>> lucky_integer(1, 1, 1, 3) + -1 + """ + counter = Counter(integers) + try: + return max(i for i in set(integers) if i == counter[i]) + except ValueError: + return -1 + + +if __name__ == "__main__": + import doctest + + doctest.testmod(verbose=True) diff --git a/challenge-284/steven-wilson/python/ch-2.py b/challenge-284/steven-wilson/python/ch-2.py new file mode 100644 index 0000000000..289a65148b --- /dev/null +++ b/challenge-284/steven-wilson/python/ch-2.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python3 + +from collections import Counter +from itertools import chain + + +def relative_sort(list1, list2): + """ Given two list of integers, the elements in the list2 are distinct and + also in the list1. + + Sort the elements in the list1 such that the relative order of items in + list1 is same as in the list2. Elements that is missing in list2 should be + placed at the end of list1 in ascending order. + + >>> relative_sort([2, 3, 9, 3, 1, 4, 6, 7, 2, 8, 5], [2, 1, 4, 3, 5, 6]) + [2, 2, 1, 4, 3, 3, 5, 6, 7, 8, 9] + >>> relative_sort([3, 3, 4, 6, 2, 4, 2, 1, 3], [1, 3, 2]) + [1, 3, 3, 3, 2, 2, 4, 4, 6] + >>> relative_sort([3, 0, 5, 0, 2, 1, 4, 1, 1], [1, 0, 3, 2]) + [1, 1, 1, 0, 0, 3, 2, 4, 5] + """ + counter = Counter() + not_in_2 = [] + for i in list1: + if i in list2: + counter[i] += 1 + else: + not_in_2.append(i) + + return list(chain.from_iterable([i] * counter[i] for i in list2)) + sorted(not_in_2) + + +if __name__ == "__main__": + import doctest + + doctest.testmod(verbose=True) -- cgit