惭愧,从1加到100的程序没算对,大家帮忙看看

惭愧,从1加到100的程序没算对,大家帮忙看看

rs=0
for i in range(1,100):
    rs+=i
print rs
算出来是4950
……
郁闷
原来range(1,100)是从1到99
改为range(1,101)就好了
對ah...
for i in range( 1 , 100 ) ->  i = 1  and i < 100
sum(range(1,101))
reduce(lambda x,y+y,range(1,101))
没想到还有五楼这种写法。
效率好像还不错,赞。
Help on built-in function reduce in module __builtin__:

reduce(...)
    reduce(function, sequence[, initial]) -> value
   
    Apply a function of two arguments cumulatively to the items of a sequence,
    from left to right, so as to reduce the sequence to a single value.
    For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
    ((((1+2)+3)+4)+5).  If initial is present, it is placed before the items
    of the sequence in the calculation, and serves as a default when the
    sequence is empty.