Series Summation using for loop in python

感情迁移 提交于 2020-01-24 00:54:05

问题


Let's assume this series

1+2+3+....+n

in c with for loop we can easily done this

for(i=1;i<=n;i++)
{
    sum += i;
}

in python i am able to done this using while loop

while(num <= n):

      sum += num
      num = num+1

but i can't do it using python for loop


回答1:


Python syntax is a bit different than c. In particular, we usually use the range function to create the values for the iterator variable (this is what was in Stephen Rauch's comment). The first argument to range is the starting value, the second is the final value (non-inclusive), and the third value is the step size (default of 1). If you only supply one value (e.g. range(5)) then the starting value is 0 and the supplied value is the ending one (equivalent to range(0, 5)).

Thus you can do

for i in range(1, n + 1):

to create a for loop where i takes on the same values as it did in your c loop. A full version of your code might be:

summation = 0
for i in range(1, n + 1):
    summation += i # shorthand for summation = summation + i

However, since summing things is so common, there's a builtin function sum that can do this for you, no loop required. You just pass it an iterable (e.g. a list, a tuple, ...) and it will return the sum of all of the items. Hence the above for loop is equivalent to the much shorter

summation = sum(range(1, n + 1))

Note that because sum is the name of a builtin function, you shouldn't use it as a variable name; this is why I've used summation here instead.

Because you might find this useful going forward with Python, it's also nice that you can directly loop over the elements of an iterable. For example, if I have a list of names and want to print a greeting for each person, I can do this either the "traditional" way:

names = ["Samuel", "Rachel"]
for i in range(len(names)):  # len returns the length of the list
    print("Hello", names[i])

or in a more succinct, "Pythonic" way:

for name in names:
    print("Hello", name)



回答2:


For a series build up your list then add them all together as

n = 10
sum(range(n+1))

55


For 1/n we have

n = 5
sum([1/i for i in range(1,n+1)])

2.28333


For 1/n^2 we have

n = 5
sum([1/i**2 for i in range(1,n+1)])

1.463611



来源:https://stackoverflow.com/questions/49641763/series-summation-using-for-loop-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!