0

How can i define function its parameter for in each case?

for example abs() abs(-5) = abs(5) = 5 abs( [ -1, 2, -3] ) = [1, 2, 3] how can i define my function like abs function ? ? ? I need to use it. i hope to use it def myFunc() '''not yet implement... :<''' myFunc(50) = some value lst = [10, 20, 30] myFunc(lst) = list of calculated values very difficult for me...

22nd Nov 2016, 1:05 PM
Moon Hee Choi
Moon Hee  Choi - avatar
2 Respostas
+ 1
>>> def my_abs(a): if type(a) is list: return [my_abs(i) for i in a] else: return a if a>0 else -a >>> my_abs(3) 3 >>> my_abs(0) 0 >>> my_abs(-1) 1 >>> my_abs([1, -2, -7, 3]) [1, 2, 7, 3]
22nd Nov 2016, 4:28 PM
donkeyhot
donkeyhot - avatar
0
You can also make it work for any iterable object: >>> def my_abs(a): try: return [my_abs(i) for i in a] except TypeError: return a if a>0 else -a >>> my_abs(3) 3 >>> my_abs(-1) 1 >>> my_abs(0) 0 >>> my_abs([1, -2, -7, 3]) [1, 2, 7, 3] >>> my_abs((1, -2, -7, 3)) [1, 2, 7, 3] >>> my_abs(range(-3, 3)) [3, 2, 1, 0, 1, 2]
22nd Nov 2016, 4:33 PM
donkeyhot
donkeyhot - avatar