Click here to Skip to main content
15,887,430 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I do not understand the output.why isn't picking the correct array element?
0
8
1
3
2
5
11


What I have tried:

import array as arr
def sum_array(ar,n,i):
    print(i)
    print(ar[i])
    if(i>= n-1):
        return 0
    else:
        return ar[i] + sum_array(ar , n , i+1)
        
a = arr.array('i',{5,3,5,8})
n = len(a)
num = sum_array(a , n , 0)
print(num)
Posted
Updated 16-Sep-22 8:56am
Comments
Richard MacCutchan 17-Sep-22 4:55am    
You can create an array just as easily with:
a = [ 5, 3, 5, 8 ]

1 solution

When you declare your array a you are using curly brackets {} rather than square brackets []. The curly brackets is used to define a set, so first python creates a set from {5, 3, 5, 8 } which gives the set { 3, 5, 8 } which is then assigned as the contents of the array object. That means that when you take len(a) you get the value 3, rather than 4, which is what you expected.
 
Share this answer
 
Comments
CPallini 16-Sep-22 16:16pm    
5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900