Fix coding style for Project Euler problem 39 (#3023)

* improvements for project euler task 39

* add tests for solution()

* fixed a typo

* Update sol1.py

Co-authored-by: Dhruv <dhruvmanila@gmail.com>
This commit is contained in:
fa1l 2020-10-09 07:43:54 +05:00 committed by GitHub
parent c9500dc89f
commit 261be28120
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,4 +1,6 @@
"""
Problem 39: https://projecteuler.net/problem=39
If p is the perimeter of a right angle triangle with integral length sides,
{a,b,c}, there are exactly three solutions for p = 120.
{20,48,52}, {24,45,51}, {30,40,50}
@ -8,10 +10,11 @@ For which value of p ≤ 1000, is the number of solutions maximised?
from __future__ import annotations
import typing
from collections import Counter
def pythagorean_triple(max_perimeter: int) -> dict:
def pythagorean_triple(max_perimeter: int) -> typing.Counter[int]:
"""
Returns a dictionary with keys as the perimeter of a right angled triangle
and value as the number of corresponding triplets.
@ -22,19 +25,31 @@ def pythagorean_triple(max_perimeter: int) -> dict:
>>> pythagorean_triple(50)
Counter({12: 1, 30: 1, 24: 1, 40: 1, 36: 1, 48: 1})
"""
triplets = Counter()
triplets: typing.Counter[int] = Counter()
for base in range(1, max_perimeter + 1):
for perpendicular in range(base, max_perimeter + 1):
hypotenuse = (base * base + perpendicular * perpendicular) ** 0.5
if hypotenuse == int((hypotenuse)):
if hypotenuse == int(hypotenuse):
perimeter = int(base + perpendicular + hypotenuse)
if perimeter > max_perimeter:
continue
else:
triplets[perimeter] += 1
triplets[perimeter] += 1
return triplets
def solution(n: int = 1000) -> int:
"""
Returns perimeter with maximum solutions.
>>> solution(100)
90
>>> solution(200)
180
>>> solution(1000)
840
"""
triplets = pythagorean_triple(n)
return triplets.most_common(1)[0][0]
if __name__ == "__main__":
triplets = pythagorean_triple(1000)
print(f"{triplets.most_common()[0][0] = }")
print(f"Perimeter {solution()} has maximum solutions")