![]() |
get positive number from a list if there's the same number but negative - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: get positive number from a list if there's the same number but negative (/thread-6129.html) Pages:
1
2
|
RE: get positive number from a list if there's the same number but negative - haye - Nov-07-2017 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 RE: get positive number from a list if there's the same number but negative - heiner55 - Nov-07-2017 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. RE: get positive number from a list if there's the same number but negative - haye - Nov-07-2017 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) RE: get positive number from a list if there's the same number but negative - heiner55 - Nov-07-2017 def test(lis): m = min(lis, key=abs) return abs(m) if -m in lis else m RE: get positive number from a list if there's the same number but negative - ineedastupidusername - Nov-08-2017 ![]() 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 ![]() ![]() ![]() |