Python Forum

Full Version: get positive number from a list if there's the same number but negative
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
yes, sorry, i meant : "if m in lis and -m in lis:"
but anyways, you're right, i just need " if -m in lis: "
thanks for help
You wrote in your first post:
   Is there a simpler way?

What do you mean with simple:
a. less code
b. code should run faster

If b:
   Your code runs twice over the list.
   I assume there is an algorithm
   that runs only once over the list.
i wanted a shorter code but doing the same as the one i used firstly which was :
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)
now i have:

list_one = [-8, 8, 144, 17]
def test(lis):
    m = min(lis, key=abs)
    if -m in lis:
        return abs(m)
    else:
        return m
 
print test(list_one)
def test(lis):
    m = min(lis, key=abs)
    return abs(m) if -m in lis else m
My code loops through list once and seems to handle all cases (just returns [0] if there's a zero in there etc):
a=[-16,4,16,7,-4]
def getzeroclosest(a):
    negmax=None
    posmin=None
    for n in a:
        if n==0:
            return [0]
        elif n<0:
            if negmax==None:
                negmax=n
            if n>negmax:
                negmax=n
        elif n>0:
            if posmin==None:
                posmin=n
            if n<posmin:
                posmin=n
    if -negmax==posmin:
        return [posmin,negmax]
    elif -negmax<posmin:
        return [negmax]
    else:
        return [posmin]
print getzeroclosest(a)
Thanks for reading My code that I typed with My fingers on My keyboard. Yeah right, there's no self ownership in this totalitarian world, none of those things are mine, we're all slaves.
Pages: 1 2