This is my code for solving the pentagonal number problem on Project Euler:
Pentagonal numbers are generated by the formula, \$P_n=n\dfrac{3n−1}{2}\$.
The first ten pentagonal numbers are:
1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ...
It can be seen that
P4 + P7 = 22 + 70 = 92 = P8
. However, their difference,70 − 22 = 48
, is not pentagonal.Find the pair of pentagonal numbers, \$P_j\$ and \$P_k\$, for which their sum and difference are pentagonal and \$D = |P_k − P_j|\$ is minimized; what is the value of \$D\$?
As a beginner, I use the most basic concepts so often that sacrifices efficiency. If I could get some general tips on improving this code that would be awesome.
Key things I'd like to improve on:
How to deal with double for loops when using elements from 2 lists:
for x in a:
for y in b:
And if there are any functions built into Python that I could use to instead of the bit of code written.
lst = []
dic = []
test = []
Final = []
for x in range(1, 3010):
thing = int((x * (3*x - 1))/2)
test.append(thing)
test = set(test)
for x in range(1, 3001):
num = int((x * (3*x - 1))/2)
lst.append(num)
lst = set(lst)
list2 = lst
for x in lst:
for y in list2:
num = x + y
num2 = abs(x - y)
dic.append({num: num2})
dic = [dict(t) for t in set([tuple(d.items()) for d in dic])]
for x in dic:
for y in x:
if y in test:
Final.append(x)
for x in Final:
for y in x:
if x[y] in test:
print(x)