diff --git a/EXERCISES.txt b/EXERCISES.txt index b00b09fc8d..3c5f5923ea 100644 --- a/EXERCISES.txt +++ b/EXERCISES.txt @@ -18,6 +18,7 @@ sum-of-multiples space-age grains gigasecond +palindrome-products triangle scrabble-score sieve diff --git a/palindrome-products/example.py b/palindrome-products/example.py new file mode 100644 index 0000000000..6d209b7f0f --- /dev/null +++ b/palindrome-products/example.py @@ -0,0 +1,18 @@ +def largest_palindrome(max_factor, min_factor=0): + return max(palindromes(max_factor, min_factor), key=lambda tup: tup[0]) + + +def smallest_palindrome(max_factor, min_factor): + return min(palindromes(max_factor, min_factor), key=lambda tup: tup[0]) + + +def palindromes(max_factor, min_factor): + return ((a * b, (a, b)) + for a in range(min_factor, max_factor + 1) + for b in range(min_factor, a + 1) + if is_palindrome(a * b)) + + +def is_palindrome(n): + s = str(n) + return s == s[::-1] diff --git a/palindrome-products/palindrome_products_test.py b/palindrome-products/palindrome_products_test.py new file mode 100644 index 0000000000..9927e5323e --- /dev/null +++ b/palindrome-products/palindrome_products_test.py @@ -0,0 +1,50 @@ +""" +Notes regarding the implementation of smallest_palindrome and +largest_palindrome: + +Both functions must take two keyword arguments: + max_factor -- int + min_factor -- int, default 0 + +Their return value must be a tuple (value, factors) where value is the +palindrome itself, and factors is an iterable containing both factors of the +palindrome in arbitrary order. +""" + +try: + from palindrome import smallest_palindrome, largest_palindrome +except ImportError: + raise SystemExit('Could not find palindrome.py. Does it exist?') + +import unittest + + +class PalindromesTests(unittest.TestCase): + def test_largest_palindrome_from_single_digit_factors(self): + value, factors = largest_palindrome(max_factor=9) + self.assertEqual(9, value) + self.assertIn(set(factors), [{1, 9}, {3, 3}]) + + def test_largest_palindrome_from_double_digit_factors(self): + value, factors = largest_palindrome(max_factor=99, min_factor=10) + self.assertEqual(9009, value) + self.assertEqual({91, 99}, set(factors)) + + def test_smallest_palindrome_from_double_digit_factors(self): + value, factors = smallest_palindrome(max_factor=99, min_factor=10) + self.assertEqual(121, value) + self.assertEqual({11}, set(factors)) + + def test_largest_palindrome_from_triple_digit_factors(self): + value, factors = largest_palindrome(max_factor=999, min_factor=100) + self.assertEqual(906609, value) + self.assertEqual({913, 993}, set(factors)) + + def test_smallest_palindrome_from_triple_digit_factors(self): + value, factors = smallest_palindrome(max_factor=999, min_factor=100) + self.assertEqual(10201, value) + self.assertEqual({101, 101}, set(factors)) + + +if __name__ == '__main__': + unittest.main()