- #1

- 2,168

- 193

I wrote a piece of code to solve the problem but it still takes too much time to solve it Any ideas how can I improve my code, like adjustments that I can make ?

Code:

```
import itertools
import time
start = time.perf_counter()
def prime(N):
if N == 0 or N == 1 or N == 5:
return False
for i in range(2, int(N ** 0.5) + 1):
if N % i == 0:
return False
return Truedef dig_sum(j, n): # j is the number, n is the element in the list as tuple
d = 0
if j == 0:
for k in n:
d += sum(int(digit) for digit in str(k))
if d%3 == 0:
return False
return True
else:
s = sum(int(digit) for digit in str(j))
for k in n:
w = s + sum(int(digit) for digit in str(k))
if w % 3 == 0:
return False
return Truedef con_test(j, n): # j is the number, n is the element in the list as tuple
if j == 0:
w = int(str(n[0]) + str(n[1]))
w1 = int(str(n[1]) + str(n[0]))
if prime(w) == False or prime(w1) == False:
return False
return True
else:
for i in n:
w = int(str(j) + str(i))
w1 = int(str(i) + str(j))
if prime(w) == False or prime(w1) == False:
return False
return Truedef st(n): #to get rid of the repeated elements
H = [tuple(sorted(i)) for i in n]
G = set(H)
return GPrimes = [i for i in range(3,8000) if prime(i) == True] #Prime range
Com_two = list(itertools.combinations(Primes,2))
G2 = [i for i in Com_two if dig_sum(0,i) == True and con_test(0,i) == True]
G2r = st(G2)
G3 = [(i,*j) for i in Primes for j in G2r if dig_sum(i,j) == True and con_test(i,j) == True ]
G3r = st(G3)
G4 = [(i,*j) for i in Primes for j in G3r if dig_sum(i,j) == True and con_test(i,j) == True ]
G4r = st(G4)
G5 = [(i,*j) for i in Primes for j in G4r if dig_sum(i,j) == True and con_test(i,j) == True ]
F = [(sum(j),j) for j in G5]
end = time.perf_counter()
Time = end-start
print(Time)
print(F)
```

When I set Primes range to 8000 it took 18 min to give an answer I checked the solution for the 4 set of primes and it gives me the right result.(If you want to check print (G4r))

Any ideas how can I make my program faster ?