Reputation: 1
I got problem in a technical assessment. The base code(already written) looks someting like this.
count=0
def findthesum(a,n):
global count
sum=0
'''
write your code here
'''
return sum
def main():
global count
n=5
a=[1,2,3,4,5]
print(count)
print(findthesum(a,n))
main()
I have to write my logic at specified position inside the code. My code looked something like this.
count=0
def findthesum(a,n):
global count
sum=0
l=[]
for i in range(31):
l.append(2**i)
for j in range(n):
if(a[j] in l):
count=count+1
sum=sum+a[j]
return sum
def main():
global count
n=5
a=[1,2,3,4,5]
print(count)
print(findthesum(a,n))
main()
I was unable to increment the value of value of count variable even after declaring it global.
What the issue with this and how to fix this?
Upvotes: 0
Views: 735
Reputation: 1049
count=0
def findthesum(a,n):
global count
sum=0
for i in range(n):
sum+=a[i]
count+=1
print(count, end= '')
print(f' The sum is: ' + str(sum))
def main():
global count
n=5
a=[1,2,3,4,5]
print(count)
print(findthesum(a,n))
main()
--> '12345 The sum is: 15'
Upvotes: 1
Reputation: 81
Are You trying to sum all the element? If yes, then:
count=0
a=[1,2,3,4,5]
n=5
def counting(li, le):
for i in range(le):
try:
count+=li[i-1]
except:
pass
else:
pass
return count
counting(a, n)
Upvotes: 0