From 0b485706acdd66590b293ff90d7f6a4b489d55c2 Mon Sep 17 00:00:00 2001 From: Steven Date: Mon, 22 Apr 2024 17:27:40 +0100 Subject: add solutions week 266 in python --- challenge-266/steven-wilson/python/ch-1.py | 30 +++++++++++++++++++++++ challenge-266/steven-wilson/python/ch-2.py | 39 ++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+) create mode 100644 challenge-266/steven-wilson/python/ch-1.py create mode 100644 challenge-266/steven-wilson/python/ch-2.py diff --git a/challenge-266/steven-wilson/python/ch-1.py b/challenge-266/steven-wilson/python/ch-1.py new file mode 100644 index 0000000000..8ed85e183a --- /dev/null +++ b/challenge-266/steven-wilson/python/ch-1.py @@ -0,0 +1,30 @@ +#!/usr/bin/env python3 + +from collections import Counter + + +def uncommon_words(*sentences): + ''' Given two sentences, find all uncommmon words in any order in the + given two sentences. Return ('') if none found. A word is uncommon if it + appears exactly once in one of the sentences and doesn’t appear in other + sentence. + + >>> uncommon_words('Mango is sweet', 'Mango is sour') + ['sweet', 'sour'] + >>> uncommon_words('Mango Mango', 'Orange') + ['Orange'] + >>> uncommon_words('Mango is Mango', 'Orange is Orange') + [''] + ''' + if not sentences: + raise TypeError('Provide at least one sentence.') + + counter = Counter(word for sentence in sentences for word in sentence.split()) + uncommon = [word for word, count in counter.items() if count == 1] + return uncommon if uncommon else [''] + + +if __name__ == "__main__": + import doctest + + doctest.testmod(verbose=True) diff --git a/challenge-266/steven-wilson/python/ch-2.py b/challenge-266/steven-wilson/python/ch-2.py new file mode 100644 index 0000000000..f6603f73a4 --- /dev/null +++ b/challenge-266/steven-wilson/python/ch-2.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python3 + + +def is_x_matrix(matrix): + ''' Given a square matrix, find if the given matrix is X Matrix. A square + matrix is an X Matrix if all the elements on the main diagonal and + antidiagonal are non-zero and everything else are zero + + >>> is_x_matrix([[1, 0, 0, 2], [0, 3, 4, 0], [0, 5, 6, 0], [7, 0, 0, 1],]) + True + >>> is_x_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9],]) + False + >>> is_x_matrix([[1, 0, 2], [0, 3, 0], [4, 0, 5],]) + True + ''' + matrix_size = len(matrix) + diagonal_position = 0 + for row in matrix: + antidiagonal_position = matrix_size - diagonal_position - 1 + x = [] + if diagonal_position < antidiagonal_position: + x.append(row.pop(antidiagonal_position)) + x.append(row.pop(diagonal_position)) + elif diagonal_position == antidiagonal_position: + x.append(row.pop(diagonal_position)) + else: + x.append(row.pop(diagonal_position)) + x.append(row.pop(antidiagonal_position)) + if not all(elem != 0 for elem in x) or not all(elem == 0 for elem in row): + return False + diagonal_position += 1 + + return True + + +if __name__ == "__main__": + import doctest + + doctest.testmod(verbose=True) -- cgit