Jawndoyghboi1569 - 1 month ago 7

Python Question

`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`

For example, let's say the input is

`[-1,2,-3,4,-5]`

`[-1,8,-27,64,-125]`

`[-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`

`list`

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([])
# []
```

Source (Stackoverflow)

Comments