简体   繁体   中英

Custom minimum function is not returning my negative inputs and just return zero? how can i fix my code?

My mission is to create a function that return the minimum number from a list without using the min() function. When i run the following code, it return 0 instead of -1. I am not too sure why. Note: 1. fancy_min just returns the smaller number between the two parameters given. 2. If the list is empty or if the parameter is None, I want to return None.

def minimum_of(numbers):
  mini = 99999999
  if numbers == []:
    return None
  elif numbers is None:
    return None
  for i in range(len(numbers)-1):
    m = fancy_min(numbers[i], numbers[i+1])
  if m<mini:
    return m

print(minimum_of([-1,3,None,2,1,]))

def fancy_min(a, b):
  while a is None:
    return b
  while b is None:
    return a
  if a > b:
    return b
  elif b > a:
    return a

Your code returns min of last two numbers. Try this:

def fancy_min(a, b):
  if a is None:
    return b
  if b is None:
    return a
  if a > b:
    return b
  elif b > a:
    return a

def minimum_of(numbers):
  mini = 99999999
  if numbers == []:
    return None
  elif None in numbers:
    return None 
  for i in range(len(numbers)):
    mini = fancy_min(numbers[i], mini)
  return mini

You don't actually need two functions for this, and the None list item constraint can be handled much more succinctly using the built-in function filter .

def new_min(l=None):
    if not l:
        return None

    m = None
    for n in filter(lambda x: x is not None, l):
        if (m is None) or (n < m):
            m = n

    return m

Running on example data:

new_min([-1,3,None,2,1,])
> -1
new_min([None, None]) is None
> True
new_min(None) is None
> True
new_min() is None
> True

If you want to dig a little deeper in the link above, you can also get the minimum this way (though this ignores the case where the argument itself is None or contains no non- None values):

reduce(
    lambda a, b: a if (a < b) else b,
    filter(lambda x: x is not None, l)
) or None

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM