My basic recursion function is like this:
input_string would be in this format = [ [cow pig donkey], 'pig dog']
keep_track = []
def recursion(input_string, finding_name):
list_names = list format
[cow pig donkey], [pig], [dog]
for item in list_names:
if item is A SINGLE WORLD:
ie [pig]
if name is finding_name:
keep_track append name
else name is A LIST WITH MULTIPLE WORDS:
ie [cow pig donkey]
recursion([cow pig donkey], finding_name)
[cow], [pig], [donkey]
This is where I'm getting stuck. Since I have a return statement at the end
return keep_track
my function is returning multiple times if my recursion is called. I'm not sure how to fix my function so that I only return once.
FUNCTION WITHOUT THE COMMENTS
keep_track = []
def recursion(input_string, finding_name):
list_names = basically would do this the first time
for item in list_names:
if item is A SINGLE WORLD:
if name is finding_name:
keep_track append name
else name is A LIST WITH MULTIPLE WORDS:
recursion(item, finding_name)
return list_names
Your question is a mess so it's very difficult to understand what you're trying to ask. An hour later, it's still not clear. I'm going to make a best-guess attempt at answering what appears to be the question.
It seems you've been given a list of strings nested arbitrarily deep. Something like:
in_lst = ['horse', 'cow', 'dog', ['pig', 'pig', 'horse'], 'cat', 'sheep']
And you want to end up with a list containing all the occurrences of a particular string
foo(in_lst, "pig") == ["pig", "pig"]
foo(in_lst, "horse") == ["horse", "horse"]
foo(in_lst, "dog") == ["dog"]
The easiest way to do that is probably to flatten the list, then filter (rather than recurse directly).
# Python3.3+
def flatten(lst):
for el in lst:
try:
yield from flatten(el)
except TypeError:
yield el
# Python3, before 3.3
def flatten(lst):
accum = []
for el in lst:
if hasattr(el, "__iter__") and not isinstance(el, str):
accum.extend(flatten(el))
else:
accum.append(el)
return accum
# Python2
def flatten(lst):
# same as Python3 before 3.3, except replace
...
if hasattr(el, "__iter__") and not isinstance(el, str):
# with
...
if hasattr(el, "__iter__") and not isinstance(el, basestring):
def find_names(haystack, needle):
return filter(lambda el: el==needle, flatten(haystack))
# or return [el for el in flatten(haystack) if el == needle]
if you MUST recurse directly for some reason (hint: don't), then try the same method I used when flattening:
def find_names(haystack, needle):
accum = []
for el in lst:
if hasattr(el, "__iter__") and not isinstance(el, str):
accum.extend(find_names(el, needle))
elif el == needle:
accum.append(el)
return accum
Although arguably it might be easier to just count.
def find_names(haystack, needle):
return [needle] * sum(1 for el in flatten(haystack) if el==needle)
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.