I have these 2 simple functions to sum and count list elements without using standard python commands like sum() and len() .
#sum the elements of a list
def sum_list(x):
n=0
for i in x:
n= n+i
return n
ex. if x=[1,5] - should return 6
#count the number of elements in a list
def count_list(x):
n=0
for i in x:
n= n+1
return n
ex. if x=[1,5] - should return 2
The problem is I cant understand how they work. More specifically:
1) What does n=0 represents before the loop? Is it some kind of starting point?
2) After that, I can understand what the for-loop does, but I cant get what the n= n+i and n=n+1 actually means. What is "n" in this case, and why if I add "i" (n+i) gives the sum while adding "1" (n+1) gives the length of the list?
Make use of print statements to help you understand how the loop is working. (copy paste the code and run) To answer you questions
n -> is the variable that holds the values of n+i
and n+1
, so value of n+i
and n+1
gets stored in n
(The code moves left to right). You can think of it as a starting point
so n+i
or n+1
does the computation needed and stores the number in n
and then returns it in the next step.
To answer you question "why if I add "i" (n+i) gives the sum while adding "1" (n+1) gives the length of the list?" : i
will keep changing with every loop iteration but in n+1
, only n
changes everytime. Therefore sum function gives you the sum and the count function gives you the length.
You can use len
to get the number of elements in a list
Hope this helps.
I have added more print statements to help you understand it better, run the code and see if it helps.
def sum_list(x):
print("SUM FUNCTION START")
n = 0
for i in x:
print("n: ",n)
print("i: ",i)
n = n + i
print("n =",n,",","i= ",i)
print("n + i = ",n)
print()
print("SUM FUNCTION END")
print()
return n
def count_list(x):
print()
print("COUNT FUNCTION START")
n = 0
for i in x:
print("n: ",n)
print("i: ",i)
print("n =",n,",","i= ",i)
print("n + 1 = ",n)
n = n + 1
print()
print("COUNT FUNCTION END")
return n
#EASIER WAY TO COMPUTER LENGTH OF THE LIST USING len FUNCTION
def count_list2(x):
return len(x)
def main():
x = [1,2,3,4,5]
answer = sum_list(x)
print("Sum : ", answer)
elements = count_list(x)
elements2 = count_list2(x)
print()
print("There are", elements, "elements in the list")
print()
print("There are", elements2, "elements in the list")
main()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.