As a self-teaching Python beginner for almost 4 months, I have mostly been doing online challenges including Project Euler problems.
Problem 45 asks:
Triangle, pentagonal, and hexagonal numbers are generated by the following formulae:
$$ \begin{array}{lll} \textrm{Triangle} & T_n=n(n+1)/2 & 1, 3, 6, 10, 15, \ldots \\ \textrm{Pentagonal} & P_n=n(3n−1)/2 & 1, 5, 12, 22, 35, \ldots \\ \textrm{Hexagonal} & H_n=n(2n−1) & 1, 6, 15, 28, 45, \ldots \\ \end{array} $$
It can be verified that \$T_{285} = P_{165} = H_{143} = 40755\$.
Find the next triangle number that is also pentagonal and hexagonal.
I encountered this problem and was able to write the code without much problem although most of the solutions I write are mostly brute force. However I am not satisfied with the time the coding took to find the answer as it took 530.7 seconds to find the solution with this code:
import time
startTime = time.time()
limit = 1000000
triangle = []
pentagonal = []
hexagonal = []
triangle_number = []
class Shape:
def __init__(self, term):
self.term = term
def triangle(self):
return int(self.term * (self.term + 1) / 2)
def pentagonal(self):
return int(self.term * (3 * self.term -1) / 2)
def hexagonal(self):
return int(self.term * (2 * self.term - 1))
def generate():
for terms in range(1, limit + 1):
product = Shape(terms)
triangle.append(product.triangle())
pentagonal.append(product.pentagonal())
hexagonal.append(product.hexagonal())
def main():
generate()
for _, terms in enumerate(hexagonal):
if len(triangle_number) == 3:
break
elif terms in triangle and terms in pentagonal:
triangle_number.append(terms)
print(terms)
print(triangle_number)
print(time.time() - startTime, "seconds")
main()
I am aware that using the class is unecessary for this problem, but I want to include it as a practice of getting used to writing solutions that require classes.
Alternatively I have re-written another solution of this problem without any classes included but keeping the same style, however it still took 328.2 seconds.
So what suggestions are there to improve the code to run faster? I have tried to review other solutions from the solution page however I do not understand how it was simplified so much to make it run more efficient.