Posts: 27
Threads: 8
Joined: Sep 2017
Nov-07-2017, 02:28 PM
(This post was last modified: Nov-07-2017, 02:28 PM by haye.)
list_one = [-8, 8, 144, 17]
def test(lis):
return min(lis, key=abs)
print test(list_one) Output: -8
i want to print the closest number to 0 from a list,
in this case, -8 and 8 are the two closest number to 0, but i get the first number of the list(-8), and i would like that if there is two numbers which are as close each other to 0 (so like in this case, -8 and 8) I'd like to get the positive number ( so 8 )
how could i do that , thanks
well, resolved doing this,
list_one = [-8, 8, 144, 17]
def test(lis):
m = min(lis, key=abs)
if m < 0:
if m and m*-1 in lis:
return m*-1
else:
return m
else:
return m
print test(list_one) new output :
Output: 8
was there a simpler way ?
Posts: 2,130
Threads: 11
Joined: May 2017
Yes
list_one = [-8, 8, 144, 17]
min(filter(lambda x: x >= 0, list_one))
Posts: 27
Threads: 8
Joined: Sep 2017
i will look at it , thanks
Posts: 606
Threads: 3
Joined: Nov 2016
With the list = [-8, 144, 17]
I get -8 with first programm
and 17 with second program.
Posts: 27
Threads: 8
Joined: Sep 2017
hi heiner, this is weird, it's not the case for me,
with first program, i get -8
with second program, -8 too
Posts: 606
Threads: 3
Joined: Nov 2016
Take my list = [-8, 144, 17], not the original one.
Posts: 27
Threads: 8
Joined: Sep 2017
this is what i did :
list_one = [-8, 144, 17]
def test(lis):
return min(lis, key=abs)
print test(list_one) Output: -8
----
list_one = [-8, 8, 144, 17]
def test(lis):
m = min(lis, key=abs)
if m < 0:
if m and m*-1 in lis:
return m*-1
else:
return m
else:
return m
print test(list_one) Output: -8
Posts: 606
Threads: 3
Joined: Nov 2016
Nov-07-2017, 04:41 PM
(This post was last modified: Nov-07-2017, 04:41 PM by heiner55.)
Sorry, with second program, I meant this:
list_one = [-8, 144, 17]
print(min(filter(lambda x: x >= 0, list_one)))
Posts: 27
Threads: 8
Joined: Sep 2017
oh yes, you're right, it seems to work only for positives numbers, i finally used this way:
list_one = [-8, 8, 144, 17]
def test(lis):
m = min(lis, key=abs)
if m and -m in lis:
return abs(m)
else:
return m
print test(list_one) Output: 8
and with you're list:
list_one = [-8, 144, 17]
def test(lis):
m = min(lis, key=abs)
if m and -m in lis:
return abs(m)
else:
return m
print test(list_one) Output: -8
Posts: 606
Threads: 3
Joined: Nov 2016
Nov-07-2017, 05:25 PM
(This post was last modified: Nov-07-2017, 05:34 PM by heiner55.)
Why
if m and -m in lis:
and not only:
if -m in lis:
?
I think "if m" is always true (except 0).
Or did you mean:
if m in list and -m in list:
|