Jawndoyghboi1569 Jawndoyghboi1569 - 1 month ago 7
Python Question

Confusing bug with brackets on my function

def cube_of(valz):    
    '''Returns the cube of values'''    
    if len(valz) == 0:    
        return 0    
    else:    
        new_val = [valz[0] ** 3]    
        return  [new_val] + [cube_of(valz[1:])] 


So I am making this function for a demonstration which takes a list of values called
valz
and takes the cube of each value and then returns a list of these cubes.

For example, let's say the input is
[-1,2,-3,4,-5]
- it should return
[-1,8,-27,64,-125]
but it returns
[-1, [8, [-27, [64, [-125, 0]]]]]
.
What is causing the extra brackets? If I remove the brackets in the code then it either gives the sum of these cubes (which is not correct) or it gives an error (something about adding an
int
to a
list
). I tried to debug this and even had my friend take a look but we're both pretty stumped.

Answer

If valz is empty you should return empty list instead of 0 - return []

new_valz is a list so you don't need brackets. cube_of returns list so you don't need brackets too.

def cube_of(valz):    
    '''Returns the cube of values'''    
    if len(valz) == 0:    
        return []    
    else:    
        new_val = [valz[0] ** 3]    
        return  new_val + cube_of(valz[1:])

cube_of([-1,2,-3,4,-5])
# [-1,8,-27,64,-125]

cube_of([])
# []
Comments