Skip to content

Hacktoberfest 2020 - coding style for project_euler problem 39 #3023

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Oct 9, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 22 additions & 7 deletions project_euler/problem_39/sol1.py
Original file line number Diff line number Diff line change
@@ -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}
Expand All @@ -8,10 +10,11 @@

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.
Expand All @@ -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")