Given a list of numbers, find the one which is closest to zero

Hello, after we have completed the video editing project we will continue to explore those websites that provide python programming training for free, one of those websites which we will explore today is called

This is the site which is about the same as the one we have visited previously, it offers game programming practice for those of you who want to become a game developer. I am still in the practice stage on this site and have just completed one of the questions on this site. If you are new to this site then you will find out that sometimes the question which the site asked is very confusing, actually it is not that hard to solve some of the problems but the site just does not give us exactly what it actually needs us to do which leaves us to figure it out the rest of the question by our self. Oh well, let us look at one of the problems from this site which I have solved.

Given a list of readings from a thermometer, find the value which is closest to zero, if there are two values that are closet to 0 and equal to each other but have different attributes, for example -2 and +2, then +2 will be the one which is closest to 0. If nothing is inside the list then just printed 0. Below is the solution for this question.

import sys
import math

a_list = [] # the list of readings
first = True
min_val = 0

for i in input().split():
    # t: a temperature expressed as an integer ranging from -273 to 5526
    t = int(i)

if(len(a_list) > 0):  
    for x in a_list:
        if(first == True):
            min_val = x
            first = False
        elif(abs(x) <= abs(min_val)):
            if((abs(x) == abs(min_val) and x > min_val) or (abs(x) < abs(min_val))):
                min_val = x
    print (min_val)


We will continue to explore this site in the next chapter. If you are interested in it then go ahead and visit it through this link!

Leave a Reply

2 Comment threads
0 Thread replies
Most reacted comment
Hottest comment thread
2 Comment authors
Pedro Romeroadrian Recent comment authors
newest oldest most voted
Notify of

More pythonic solution imho:

input_data = list(map(int, input().split()))
min_value = min(input_data , key=lambda x: (abs(x), -x)) if input_data else 0

Pedro Romero
Pedro Romero

buenos dias de casualidad n ose podria usar un reduce…?