S
S
Sunter2021-06-05 17:49:36
Python
Sunter, 2021-06-05 17:49:36

How can I optimize the code from the USE task?

60bb8d8a60686873014354.png

k = 0
maximum = 0
cmaximum = 0
for c in range(1,5001):
    for b in range(1,c):
        for a in range(1,b):
            if c**2 == a**2+b**2:
                k = k + 1
                if maximum < a+b+c:
                    maximum = a +b+c
                    cmaximum = c
print(k,cmaximum)

The program, preferably, should work less than 5 minutes, without using non-built-in libraries

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
sswwssww, 2021-06-05
@Sunter

from itertools import combinations

sq = {e**2: e for e in range(1, 5001)}
maximum = 0
cmaximum = 0
count = 0

for a, b in combinations(sq, 2):
    ab = a + b
    if ab in sq:
        count += 1
        tmp_maximum = sq[a] + sq[b] + sq[ab]
        cmaximum, maximum = (sq[ab], tmp_maximum) if tmp_maximum > maximum else (cmaximum, maximum)
print(count, cmaximum)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question