我在一次技术评估中遇到了问题。基本代码(已经编写(看起来像这样。
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()
我必须在代码中的指定位置写我的逻辑。我的代码看起来像这样。
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()
即使在声明count变量为全局变量后,我也无法增加它的值。
这有什么问题,如何解决?
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'
您正在尝试对所有元素求和吗?如果是,则:
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)