Python程序查找数组的总和
给定一个整数数组,求其元素之和。
例子 :
Input : arr[] = {1, 2, 3}
Output : 6
1 + 2 + 3 = 6
Input : arr[] = {15, 12, 13, 10}
Output : 50
方法一:
# Python 3 code to find sum
# of elements in given array
def _sum(arr):
# initialize a variable
# to store the sum
# while iterating through
# the array later
sum=0
# iterate through the array
# and add each element to the sum variable
# one at a time
for i in arr:
sum = sum + i
return(sum)
# driver function
arr=[]
# input values to list
arr = [12, 3, 4, 15]
# calculating length of array
n = len(arr)
ans = _sum(arr)
# display sum
print ('Sum of the array is ', ans)
# This code is contributed by Himanshu Ranjan
输出:
Sum of the array is 34
方法二:
# Python 3 code to find sum
# of elements in given array
# driver function
arr = []
# input values to list
arr = [12, 3, 4, 15]
# sum() is an inbuilt function in python that adds
# all the elements in list,set and tuples and returns
# the value
ans = sum(arr)
# display sum
print ('Sum of the array is ',ans)
# This code is contributed by Dhananjay Patil
输出:
Sum of the array is 34
有关详细信息,请参阅有关程序的完整文章以查找给定数组中的元素总和!