需要将两个函数合并为一个(Python) [英] Need to combine two functions into one (Python)

查看:673
本文介绍了需要将两个函数合并为一个(Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码 -

  def Max(lst):
if len(lst)== 1 :
return lst [0]
else:
m = Max(lst [1:])
if m> lst [0]:
return m
else:
return lst [0]
def Min(lst):
如果len(lst)== 1:
return lst [0]
else:
m = Min(lst [1:])
if m< lst [0]:
return m
else:
return lst [0]
print(Max number:,Max([5,4,100,0,2]) )
print(Min number:,Min([5,4,100,0,2]))

基本上我需要一个返回最大和最小数字的函数,它需要递归。我怎样才能改变这段代码?

有些类型的递归算法/ 如果你知道诀窍,很容易想出来。这个技巧是:


假设你已经有了一个可以做你想要的功能。


等等,不,没有意义,是吗?然后我们已经完成了。



让我们再试一次:


假设你已经有了一个可以做你想做的功能(但是 only ,对于输入1的元素比你需要的小)


在那里,好多了。虽然有点愚蠢,但这是一个我们可以使用的假设。



我们想要什么 do ?在你的例子中,它返回列表的最小和最大元素。假设我们希望他们作为2元组(又名对)返回:

  lst = [5,4, 100,0,2] 

#实际上,我们只能按照上面的假设对较小的列表
#做这件事。
lst = lst [1:]

lst_min,lst_max = magic_min_max(l)#我想要一只小马!

assert lst_min == 0#一厢情愿的想法
assert lst_max == 100#一厢情愿的想法

如果我们有这样一个神奇功能,我们可以用它来解决实际输入大小的问题吗?让我们试试:

  def real_min_max(lst):
candidate = lst [0]
rest_of_the_list = lst [1:]
min_of_rest,max_of_rest = magic_min_max(rest_of_the_list)#允许,因为
#小于lst
min_of_lst =候选人,如果候选人< min_of_rest else min_of_rest
max_of_lst =候选人候选人> max_of_rest else max_of_rest
return min_of_lst,max_of_lst

并不简单,但非常简单,isn是吗? 但是让我们假设我们的魔术函数 magic_min_max 有一个额外的限制:它不能处理空列表。(毕竟,一个空列表不是 既不是最小也不是最大元素,即使 magic 也不能改变它。)所以如果 lst 的大小为1,我们不能调用魔术函数。尽管如此,我们没问题。这种情况很容易检测到。单个元素既是列表的最小值也是最大值,所以我们只返回它两次:

  def real_min_max(lst):
candidate = lst [0]
如果len(lst)== 1:
返回候选者,候选者#单个元素都是min&
rest_of_the_list = lst [1:]
min_of_rest,max_of_rest = magic_min_max(rest_of_the_list)#允许,因为
#小于lst
#但是(如果我们得到
#这里)不是空的
min_of_lst =候选人,如果候选人< min_of_rest else min_of_rest
max_of_lst =候选人候选人> max_of_rest else max_of_rest
return min_of_lst,max_of_lst

所以就是这样。



但是请等等...... 没有魔法。如果我们想调用一个函数,它必须实际存在。所以我们需要实现一个可以返回列表的最小值和最大值的函数,所以我们可以在 real_min_max 而不是 magic_min_max 。由于这是关于递归的,你知道解决方案: real_min_max 该函数(一旦通过调用 存在),所以我们可以自己调用它:

  def real_min_max(lst):
candidate = lst [ 0]
if len(lst)== 1:
return candidate,candidate#single element is both min& max
rest_of_the_list = lst [1:]
min_of_rest,max_of_rest = real_min_max(rest_of_the_list)#无需魔法,
#只是递归!
min_of_lst =候选人,如果候选人< min_of_rest else min_of_rest
max_of_lst =候选人候选人> max_of_rest else max_of_rest
return min_of_lst,max_of_lst

让我们试试看:

  lst = [5,4,100,0,2] 
real_min_max(lst)#returns(0,100)

有用!


Here is my code-

def Max(lst):
    if len(lst) == 1:
        return lst[0]
    else:
        m = Max(lst[1:])
        if m > lst[0]: 
            return m
        else:
            return lst[0]
def Min(lst):
    if len(lst) == 1:
        return lst[0]
    else:
        m = Min(lst[1:])
        if m < lst[0]: 
            return m
        else:
            return lst[0]
print("Max number:",Max([5,4,100,0,2]))
print("Min number:",Min([5,4,100,0,2]))

Basically I need a single function that returns both the largest and smallest number and it needs to be recursively. How would would I change this code?

解决方案

Some types of recursive algorithms/implementations operating on a list input are very quite easy to come up with, if you know the "trick". That trick being:

Just assume you already have a function that can do what you want.

Wait, no, that doesn't really make sense, does it? Then we'd already be done.

Let's try that again:

Just assume you already have a function that can do what you want (but only for inputs 1 element smaller than you need).

There, much better. While a bit silly, that's an assumption we can work with.

So what do we want? In your example, it's returning the minimum and maximum elements of a list. Let's assume we want them returned as a 2-tuple (a.k.a. a "pair"):

lst = [5, 4, 100, 0, 2]

# Well, actually, we can only do this for a smaller list,
# as per our assumption above.
lst = lst[1:]

lst_min, lst_max = magic_min_max(l)  # I want a pony!

assert lst_min == 0   # Wishful thinking
assert lst_max == 100 # Wishful thinking

If we have such a magic function, can we use it to solve the problem for the actual input size? Let's try:

def real_min_max(lst):
    candidate = lst[0]
    rest_of_the_list = lst[1:]
    min_of_rest, max_of_rest = magic_min_max(rest_of_the_list) # Allowed because
                                                               # smaller than lst
    min_of_lst = candidate if candidate < min_of_rest else min_of_rest
    max_of_lst = candidate if candidate > max_of_rest else max_of_rest
    return min_of_lst, max_of_lst

Not exactly easy, but pretty straight forward, isn't it? But let's assume our magic function magic_min_max has an additional restriction: It cannot handle empty lists. (After all, an empty list doesn't have neither a minimum nor a maximum element. Not even magic can change that.)

So if lst has size 1, we must not call the magic function. No problem for us, though. That case is easy to detect and easy to circumvent. The single element is both minimum and maximum of its list, so we just return it twice:

def real_min_max(lst):
    candidate = lst[0]
    if len(lst) == 1:
        return candidate, candidate  # single element is both min & max
    rest_of_the_list = lst[1:]
    min_of_rest, max_of_rest = magic_min_max(rest_of_the_list) # Allowed because
                                                               # smaller than lst
                                                               # but (if we get
                                                               # here) not empty
    min_of_lst = candidate if candidate < min_of_rest else min_of_rest
    max_of_lst = candidate if candidate > max_of_rest else max_of_rest
    return min_of_lst, max_of_lst

So that's that.

But wait ... there is no magic. If we want to call a function, it has to actually exist. So we need to implement a function that can return the minimum and maximum of a list, so we can call it in real_min_max instead of magic_min_max. As this is about recursion, you know the solution: real_min_max is that function (once it's fixed by calling a function that does exist) so we can have it call itself:

def real_min_max(lst):
    candidate = lst[0]
    if len(lst) == 1:
        return candidate, candidate  # single element is both min & max
    rest_of_the_list = lst[1:]
    min_of_rest, max_of_rest = real_min_max(rest_of_the_list) # No magic needed,
                                                              # just recursion!
    min_of_lst = candidate if candidate < min_of_rest else min_of_rest
    max_of_lst = candidate if candidate > max_of_rest else max_of_rest
    return min_of_lst, max_of_lst

Let's try it:

lst = [5, 4, 100, 0, 2]
real_min_max(lst)  # returns (0, 100)

It works!

这篇关于需要将两个函数合并为一个(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆