课程: Python Essential Training

Solution: Sum of triangles - Python教程

课程: Python Essential Training

Solution: Sum of triangles

- [Instructor] 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 four, four squared or 16. Start with the fourth triangular number, four plus three plus two plus one, which can be arranged in a triangle four tall by four wide, and overlay this on our square. Now, if we were to get another four by four triangle and stick it on top of the square, we can see that it's too big. The diagonals overlap. However, a three by three 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 one. 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 the triangle actually calls itself, it's a recursive function. It's actually a very similar recursive function to the one we saw earlier in the factorial challenge. In fact, if I take this addition sign, change it to a multiplication sign, and just modify our base case so that if the number is equal to zero, we return one, this is in fact a factorial function. So this challenge wasn't really meant to get you bent too out of shape, but I really want to drive the point home that these same patterns appear again and again in math recursion and programming. And hopefully you'll start to recognize them and use them as you continue your journey.

内容