Hello , I have made this program to get Pythagorean triplets in user defined range but it's kinda slow and inefficient I think and this is the best that I can do . So I really appreciate everyone who would help me Increasing my code efficiency and my normal in general .
Here's the code:
def gen_pt(user_input: int):
try:
print(f'{"Pythagorean Triplets : ":<10} {"A:"} + {"B:"} = {"C:"}')
triplets = {}
for a in range(1, int(user_input) + 1):
for b in range(1, int(user_input) + 1):
for c in range(1, int(user_input) + 1):
if a**2 + b**2 == c**2:
triplets.update({(a, b): c})
print(f'{"Pythagorean Triplets : ":<10} {a}² + {b}² = {c}²')
with open('Pythagorean Triplets', 'a') as file:
for key,values in triplets.items():
file.write(f'{key} = {values} \n')
except ValueError:
print(f'{user_input} is not an integer')
user_input = input('Press ENTER to start (type "!" to stop): ')
while user_input != '!':
try:
user_input = input('Generate Pythagorean Triplets up to: ')
if user_input == '!':
break
gen_pt(user_input)
except ValueError:
if not all(char.isdigit() for char in user_input):
print('Please input numbers only!')
user_input = input('Generate Pythagorean Triplets up to: ')