Wouldn't it just be?
def triangular(n):
sum_ = 0
for i in range(n+1):
sum_+= i
return sum_
This will add all numbers from 0 to n. Though this could be put into one line:
def triangular(n):
return sum(range(n+1))
سؤال
I am struggling with what I know should be a really simple loop. I need to add all the numbers from 0 to n. The end result needs to be a positive integer, though I know if it comes out negative I can just get the absolute value to evaluate it to positive.
ex: n = 5
sum = 5 + 4 + 3 + 2 + 1
sum = 15
what I have so far is this
def triangular(n):
sum_ = 0
for i in range(n):
sum_-= n
return sum_
Any help would be greatly appreciated.
المحلول
Wouldn't it just be?
def triangular(n):
sum_ = 0
for i in range(n+1):
sum_+= i
return sum_
This will add all numbers from 0 to n. Though this could be put into one line:
def triangular(n):
return sum(range(n+1))
نصائح أخرى
The sum of numbers from 0 to N is N(N+1)/2. How about:
return n * (n+1) / 2
rather than using a loop?