addition of specific elements of a list python -


a "pyschool" exercise :

"define function calls addfirstandlast(x) takes in list of numbers , returns sum of first , last numbers."

here best solution have come with. there more elegant way write function uses built in functions?

def addfirstandlast(x):     sum_list = []     if len(x) == 0:         return 0     elif len(x) == 1 :         return int(x[0])     elif len(x) > 1 :         sum_list.append(x[0])          sum_list.append(x[-1])     return sum(sum_list) 

>>> def addfirstandlast(x): ...   return (x[0]+x[-1])/(1/len(x)+1) if x else 0 ...  >>> addfirstandlast([]) 0 >>> addfirstandlast([1]) 1 >>> addfirstandlast([1,3]) 4 

note 1 : when length of list 1 result of (1/len(x)+1) 2 divide sum of first , last elements 2 else divide 1.

note 2 : if in python 3 use // division instead /.


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -