Need to combine two functions into one (Python)

2024/11/16 22:48:47

Here is my code-

def Max(lst):if len(lst) == 1:return lst[0]else:m = Max(lst[1:])if m > lst[0]: return melse:return lst[0]
def Min(lst):if len(lst) == 1:return lst[0]else:m = Min(lst[1:])if m < lst[0]: return melse: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?

Answer

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(lst)  # 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 lstmin_of_lst = candidate if candidate < min_of_rest else min_of_restmax_of_lst = candidate if candidate > max_of_rest else max_of_restreturn 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 & maxrest_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 emptymin_of_lst = candidate if candidate < min_of_rest else min_of_restmax_of_lst = candidate if candidate > max_of_rest else max_of_restreturn 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 & maxrest_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_restmax_of_lst = candidate if candidate > max_of_rest else max_of_restreturn 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!

https://en.xdnf.cn/q/119147.html

Related Q&A

Error: descriptor blit requires a pygame.Surface object but received a NoneType [duplicate]

This question already has answers here:How can I draw images and sprites in Pygame?(4 answers)Closed 2 years ago.I am creating a game. I wrote this code to create a sprite and its hitbox:hg = pygame.i…

How can I deal with overlapping rectangles? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 5 years ago.Improve…

panda df not showing all rows after loading from MS SQL

Im using Pandas with latest sqlalchemy (1.4.36) to query a MS SQL DB, using the following Python 3.10.3 [Win] snippet: import pandas as pd # from sqlalchemy…

How to extract multiple grandchildren/children from XML where one child is a specific value?

Im working with an XML file that stores all "versions" of the chatbot we create. Currently we have 18 versions and I only care about the most recent one. Im trying to find a way to extract a…

Is there are a way to replace python import with actual sources?

I am having python files with the import statements which I would like to replace into the actual code placed in the foo.py.For instance, with the in file:from foo import Barbar = Bar() print barI woul…

How to use supported numpy and math functions with CUDA in Python?

According to numba 0.51.2 documentation, CUDA Python supports several math functions. However, it doesnt work in the following kernel function: @cuda.jit def find_angle(angles):i, j = cuda.grid(2)if i …

PYTHON - Remove tuple from list if contained in another list

I have a list of tuples:list_of_tuples = [(4, 35.26), (1, 48.19), (5, 90.0), (3, 90.0)]tuple[0] is an item_IDtuple[1] is an angleI have a list of item_IDs I want to remove/ignore from the list:ignore_I…

How to run a ij loop in Python, and not repeat (j,i) if (i,j) has already been done?

I am trying to implement an "i not equal to j" (i<j) loop, which skips cases where i = j, but I would further like to make the additional requirement that the loop does not repeat the perm…

Split a string with multiple delimiters

I have the string "open this and close that" and I want to obtain "open this and" and "close that". This is my best attempt:>>>print( re.split(r[ ](?=(open|clos…

Extracting a string between 2 chracters using python [duplicate]

This question already has answers here:Python-get string between to characters(4 answers)Closed 7 years ago.I need a Python regex to give me all the strings between ~ and ^ from a string like this:~~~~…