Python Forum
Recursive function need help
Thread Rating:
  • 2 Vote(s) - 3.5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Recursive function need help
#1
Hi All
New to coding/python, and still battling with a couple of concepts. Need some help with regards to a function that I'm meant to write.
So basically need this bottom function to work, but the code is not doing exactly what is expected. If anyone can point me in the right direction, or show me code to help me understand this better.

..... the output should be 9 not 5....

def max_val(t): 
    """ t, tuple or list
        Each element of t is either an int, a tuple, or a list
        No tuple or list is empty
        Returns the maximum int in t or (recursively) in an element of t """

    maxnum = float('-inf')
    for x in t:
        if isinstance(x, (list,tuple)):
            max_val(x)
        else:
            if x > maxnum:
                maxnum = x
    return maxnum
        
            
                    
print(max_val((5, (1,2), [[1],[9]]))) 
Reply
#2
One week before I was trying write an iterative generator, to flattening deep nested lists. The final result was this: https://stackoverflow.com/questions/2158...1#45213701

But I started with a recursive generator, which was much easier.
from collections import Iterable


def flat(iterable):
    for element in iterable:
        if isinstance(element, Iterable) and not isinstance(element, (str, bytes)):
            yield from flat(element)
        else:
            yield element
It's a more general approach. To convert this generator into an iterative generator was a bit confusing.
You can take this generator and just use min(flat(your_list)).

The yield from syntax makes it much easier to write generators, which are iterating over inalterables and/or generators.

Your example does too much. I think it's better to sort the functionality for maxnum out and do it outside of the function:
def flat_list_func(iterable):
    return_list = []
    # your new flat list
    for element in iterable:
        if isinstance(element, (list,tuple)):
            return_list.extend(flat_list_func(element))
            # here you've forgotten to return your max_val
            # I'm extending the return_list, which elements comes
            # from the recursive function call
        else:
            # if element is not list or tuple, it's appended to the
            # return_list
            return_list.append(element)
    return return_list


nested_list = (5, (1,2), [[1],[9]])
flat_list = flat_list_func(nested_list)
min_val = min(flat_list)
max_val = max(flat_list)

import statistics
mean_val = statistics.mean(flat_list)
median_val = statistics.median(flat_list)
# and much more
In general it's often easier writing recursive functions as writing the iterative counter part. In most languages we have the problem, that every function gets an own stack. If you have 32.000 functions running because of recursion, it's consuming memory. In Python the recursion depth is limited to 1000. You even have this problem in C.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#3
Thanks so much responding to my query, really is appreciated. I've looked at your code here and on stackoverflow. It looks great and would work! However, I'm completing this piece of code as an exercise.The recursive depth won't be that great, so doesn't have to be the most efficient code. What I'm really battling with is this....
I went to pythontutor.com, which is great to debug your code. So I put the code in there, and am seeing that a new "stack" is being using for the recursive parts of the code. However, the "main" maxnum is never updated from the other "stacks". So I'm wondering in particular what I'd need to do to my code to get it to work, or if I should then rethink the whole thing and do it iterativly as you've shown. However saying this the exercise as mentioned is trying to show me how to do recursive programming. If I'm not allowed to do anything outside of the function, as per your first python code on this page, what would you suggest I do?

Hope this makes sense, just bear with me being such a noob at this.... :P
Reply
#4
If you want to learn this iterative way, you should read this blog post: http://blog.moertel.com/posts/2013-05-11...ative.html
To reach this final version of the iterative generator, this article doesn't help much. I was trying to enforce myself to save memory. The other people had similar ideas. (Was reinventing the wheel).

The approach with a stack i've learned from task queues.
There is no general way to solve all recursive functions.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#5
@DeaD_EyE - thanks so much really appreciate the help. I'll go to the link and read through there, and go over your code again, to help me in my learning. Thanks once again :)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  "Plotting and Computation of Logistic Function by Using Taylor Series with Recursive canatilaa 1 1,875 May-13-2020, 04:01 PM
Last Post: jefsummers
  Recursive Function - Compare 2 lists, return the elements that don't exist in both KellyBaptist 1 5,314 Dec-23-2018, 10:10 AM
Last Post: Gribouillis
  Storing Minimum List of values from a recursive function sigsegv22 1 2,590 Sep-10-2018, 01:25 PM
Last Post: ichabod801
  Recursive function with a parameter MOH 0 2,105 Apr-30-2018, 09:39 PM
Last Post: MOH
  Recursive Function Fanki 2 3,067 Dec-06-2017, 11:40 AM
Last Post: gruntfutuk
  Recursive function janek30 1 2,939 May-16-2017, 04:58 PM
Last Post: micseydel

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020