From 261be28120712f66a5bdb643585659eb4e2f932a Mon Sep 17 00:00:00 2001 From: fa1l Date: Fri, 9 Oct 2020 07:43:54 +0500 Subject: [PATCH] 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 --- project_euler/problem_39/sol1.py | 29 ++++++++++++++++++++++------- 1 file changed, 22 insertions(+), 7 deletions(-) diff --git a/project_euler/problem_39/sol1.py b/project_euler/problem_39/sol1.py index 79fa309f0..c8ffa8934 100644 --- a/project_euler/problem_39/sol1.py +++ b/project_euler/problem_39/sol1.py @@ -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")