#🔒 How can I improve this?

11 messages · Page 1 of 1 (latest)

solemn totem
#

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: ')
frigid citrusBOT
#

@solemn totem

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

lofty crypt
#

Here's one thing you can do. Rather than re-computing a squared and b squared multiple times, do it once and save the values to variables:

        for a in range(1, int(user_input) + 1):
            a_squared = a**2
            for b in range(1, int(user_input) + 1):
                b_squared = b**2
                for c in range(1, int(user_input) + 1):
                    if a_squared + b_squared == c**2:
#

You can do a similar thing with user_input plus 1:

user_input_plus_1 = user_input + 1

#

Actually, you should just try to convert the user's input to an integer using the int() function once, before calling your gen_pt(). If you get a Value Error, then print the error.

olive star
#

You should assign value to a key instead of updating dictionary if you want to speed something up

>>> import timeit
>>> timeit.timeit("a={};a['A']=1", number=1000000)  
0.03822039999795379
>>> timeit.timeit("a={};a.update({'A':1})", number=1000000)   
0.11051210000005085

Value assignment is just faster

lament hound
#

Don't use third inner loop, just check if the sum of squares is a square (try taking a square root and check if it's int)

lofty crypt
#

Assuming that this is not a homework assignment ...

Actually, there's no need to store the information in a dictionary. As you generate the squares, you can print and write to the file at the same time. Here's an updated version:

def gen_pt(user_input: int):
    print(f'{"Pythagorean Triplets : ":<10}   {"A:"} + {"B:"}  =   {"C:"}') 

    user_input_plus_1 = user_input + 1    
    with open('Pythagorean Triplets.txt', 'a') as file:        
        for a in range(1, user_input_plus_1):
            a_squared = a**2
            for b in range(1, user_input_plus_1):
                b_squared = b**2
                for c in range(1, user_input_plus_1):
                    if a_squared + b_squared == c**2:
                        print(f'{"Pythagorean Triplets : ":<10}   {a}² + {b}²  =  {c}²')
                        file.write(f'({a}, {b}) = {c}\n')
                        break  # no need to keep checking the inner loop

while True:
    user_input = input('Generate Pythagorean Triplets up to: ')
    if user_input == '!':
        break 

    try:
        user_input = int(user_input)    
    except ValueError:
        print('Please input numbers only!')
        continue
    gen_pt(user_input)
lofty crypt
#

Turns out, that multiplication is much faster than squaring:

def gen_pt(user_input: int):
    print(f'{"Pythagorean Triplets : ":<10}   {"A:"} + {"B:"}  =   {"C:"}') 

    user_input_plus_1 = user_input + 1    
    with open('Pythagorean Triplets.txt', 'a') as file:        
        for a in range(1, user_input_plus_1):
            a_squared = a*a
            for b in range(1, user_input_plus_1):
                b_squared = b*b
                for c in range(1, user_input_plus_1):
                    if a_squared + b_squared == c*c:
                        print(f'{"Pythagorean Triplets : ":<10}   {a}² + {b}²  =  {c}²')
                        file.write(f'({a}, {b}) = {c}\n')
                        break  # no need to keep checking the inner loop

while True:
    user_input = input('Generate Pythagorean Triplets up to: ')
    if user_input == '!':
        break 

    try:
        user_input = int(user_input)    
    except ValueError:
        print('Please input numbers only!')
        continue
    gen_pt(user_input)
frigid citrusBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.