From the course: Python Essential Training
Unlock the full course today
Join today to access over 24,700 courses taught by industry experts.
Solution: Sum of triangles - Python Tutorial
From the course: Python Essential Training
Solution: Sum of triangles
The main trick in this challenge is realizing that two triangles, when put together, make a square. Now there is one other trick, and that is figuring out which triangles to use. Let's say that we want to get the square of 4, 4 squared or 16. Start with the fourth triangular number, 4 plus 3 plus 2 plus 1, which can be arranged in a triangle 4 tall by 4 wide, and overlay this on our square. Now, if we were to get another 4 by 4 triangle and stick it on top of the square, we can see that it's too big. The diagonals overlap. However, a 3 by 3 triangle fits in that corner just fine, and then we get exactly 16. In general, the square of a number, num, is equal to triangle num plus triangle num minus 1. The other thing you might have noticed is our friend recursion popping up again. So hopefully you looked at this triangle function. You didn't just take my word for it that it worked. You can see that triangle actually calls itself. It's a recursive function. It's actually a very similar…
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.