Recursive function of depth priority search does not work well in python3

Asked 2 years ago, Updated 2 years ago, 72 views

Hello, this recursive function I made with python3 doesn't work well.

def func(teleports_string):
        strings = [{n[0], n[1]} for n teleports_string.split(', ')]
        start = {'1'}

        def search(string, point, totalpoint):
            For string in strings:

                if point<=string and not string.difference(point)<=totalpoint:

                    iflen(totalpoint.union(point))>=7:

                        print(totalpoint)
                        return totalpoint

                    search(string, string.difference(point), totalpoint.union(string))
        return search (string, start, set())

func("12, 23, 34, 45, 56, 67, 78, 81")


in the above code return totalpoint
I would like to end the process with totalpoint as the return value in the line
I will start the rest of the process.
How can I end the process with return totalpoint?
Please let me know.

python algorithm

2022-09-30 21:14

1 Answers

searchYou are recursively calling yourself at the end of the function.

search(string, string.difference(point), totalpoint.union(string))

There is no return here, so we are continuing to run the outer for string in strings: even after we come back from recursive.Moreover, since the function eventually ended without a return, nothing returned (although it returned exactly None).


2022-09-30 21:14

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.