Language change and code breaks

phil hunt philh at comuno.freeserve.co.uk
Sun Jul 22 02:40:15 CEST 2001


On Fri, 20 Jul 2001 11:36:18 -0700, Corran Webster <cwebster at nevada.edu> wrote:
>
>sum = 0
>for n in range(N):
>  sum += n**2
>
>but it is useful when translating a mathematical expression like:
>
>  __ N-1   2
>  \       n
>  /__n=0
>
>into a Python program.

A better translation might be:

def fromto(f,t):
   return xrange(f,t+1)

def sum(ar):
   s = 0
   for i in ar: s += i
   return s

#and then, it's just a one-liner:

result = sum([n*n for n in fromto(0, N-1)])


-- 
#===== Philip Hunt == philh at comuno.freeserve.co.uk ======#
    Herbivore: effort-free public key encryption. See:
<http://www.vision25.demon.co.uk/oss/herbivore/intro.html>
        ** First software release coming soon! **






More information about the Python-list mailing list