Tuesday, 17 December 2024

Day 43: Python Program To Find All Pythagorean Triplets in a Given Range


 def find_pythagorean_triplets(limit):
    triplets = []
    for a in range(1, limit + 1):
        for b in range(a, limit + 1): 
            for c in range(b, limit + 1):
                if a**2 + b**2 == c**2:
                    triplets.append((a, b, c))
    return triplets

limit = int(input("Enter the range limit: "))
triplets = find_pythagorean_triplets(limit)

print("Pythagorean Triplets in the range 1 to", limit, "are:")
for triplet in triplets:
    print(triplet)
#source code --> clcoding.com 

Code Explanation:

1.Function:
find_pythagorean_triplets(limit)
Purpose:
To find all the Pythagorean triplets for numbers in the range 1 to limit.

How it works:
It initializes an empty list triplets to store valid triplets.
It uses three nested for loops to iterate through all possible values of a, b, and c such that:
a starts from 1 and goes up to limit.
b starts from a (to avoid duplicate combinations like (3,4,5) and (4,3,5)) and goes up to limit.
c starts from b (ensuring a <= b <= c to maintain order) and also goes up to limit.
If the condition is true, the triplet (a, b, c) is added to the triplets list.
Finally, the list of valid triplets is returned.

2. Input:
The user is asked to enter a positive integer limit using input(). This defines the upper range for a, b, and c.

3. Output:
The function find_pythagorean_triplets(limit) is called with the input range.
It prints all valid Pythagorean triplets found within the range 1 to limit.

Example Execution:

Input:
Enter the range limit: 20

Output:
Pythagorean Triplets in the range 1 to 20 are:
(3, 4, 5)
(5, 12, 13)
(6, 8, 10)
(8, 15, 17)
(9, 12, 15)
(12, 16, 20)

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (49) AI (34) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (173) C (77) C# (12) C++ (82) Course (67) Coursera (226) Cybersecurity (24) data management (11) Data Science (128) Data Strucures (8) Deep Learning (20) Django (14) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Google (34) Hadoop (3) HTML&CSS (47) IBM (25) IoT (1) IS (25) Java (93) Leet Code (4) Machine Learning (59) Meta (22) MICHIGAN (5) microsoft (4) Nvidia (3) Pandas (4) PHP (20) Projects (29) Python (929) Python Coding Challenge (351) Python Quiz (21) Python Tips (2) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (3) Software (17) SQL (42) UX Research (1) web application (8) Web development (2) web scraping (2)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses