Python/project_euler/problem_04/sol1.py
Edward Nuno a5000d32ed
Add style improvements to solutions for Project Euler Problem 04 (#2945)
* Fix typehints in project_euler/problem01

Squashed commit of the following:

commit 6801d073b31bf702814861cd3b07b634ca295bfa
Author: Archaengel <god11341258@gmail.com>
Date:   Mon Oct 5 16:40:10 2020 -0700

    Fix typehints in project_euler/problem01

commit 29afc3af114abd1b99dc3f7c8fc99128229db131
Author: Archaengel <god11341258@gmail.com>
Date:   Mon Oct 5 15:06:34 2020 -0700

    Add typehints and default argument for project_euler/problem_01

* Add default args, typehints, and expand variable names for PE prob 02

* Add style improvements for first solution of PE Problem 02

* Add default arg and typehints for second solution of PE Problem 02

* Add default arg for third solution of PE Problem 02

* Add style improvements for 1st soln of PE problem 03

* Add default arg and typehints for 2nd soln of PE problem 03

* Add default arg for 3rd soln of PE problem 03

* Remove unnecessary newlines

* Remove unnecessary newlines

* Fix end of file for 2nd soln in PE problem 03

* Add style improvements to solutions for PE problem 04

* Restore original newlines in soln for PE problem 04

* Fix punctuation in docstring for PE problem 04

* Restore solution bodies for PE problem 04

* Expand variable names for 2nd soln of PE problem 04
2020-10-07 10:33:34 +05:30

52 lines
1.4 KiB
Python

"""
Problem:
A palindromic number reads the same both ways. The largest palindrome made from
the product of two 2-digit numbers is 9009 = 91 x 99.
Find the largest palindrome made from the product of two 3-digit numbers which
is less than N.
"""
def solution(n: int = 998001) -> int:
"""Returns the largest palindrome made from the product of two 3-digit
numbers which is less than n.
>>> solution(20000)
19591
>>> solution(30000)
29992
>>> solution(40000)
39893
>>> solution(10000)
Traceback (most recent call last):
...
ValueError: That number is larger than our acceptable range.
"""
# fetches the next number
for number in range(n - 1, 9999, -1):
# converts number into string.
str_number = str(number)
# checks whether 'str_number' is a palindrome.
if str_number == str_number[::-1]:
divisor = 999
# if 'number' is a product of two 3-digit numbers
# then number is the answer otherwise fetch next number.
while divisor != 99:
if (number % divisor == 0) and (len(str(number // divisor)) == 3.0):
return number
divisor -= 1
raise ValueError("That number is larger than our acceptable range.")
if __name__ == "__main__":
import doctest
doctest.testmod()
print(solution(int(input().strip())))