Exercise: Sum up integer powers

Task: Write a code to compute the value of $$ \sum_{n=1}^N n^i $$ for any integers $i$ and $N$. (Solution codes will be ranked in terms of correctness, readability, and brevity.)

How do you know your answer is correct? When writing code it is important to check for correctness. Llementary mathematics tells us that $$ \sum_{n=1}^N n^2 = \frac N 6 (N+1) (2N +1). $$ (If you don't know this prove it!) So you can easily check that your code gives the correct answer, at least for $i=2$. In fact, even for a general power $i$, power sums have been studied very well and expressions connecting them to the Riemann zeta function are well known, so for this task, there are indeed many sources to double check our code results.

Python has many styling guidelines for writing good code. You may want to peruse PEP 8 at your leisure. And take time to behold an easter egg (one of several) within the language:

In [1]:
import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!