Python Forum
Thread Rating:
  • 2 Vote(s) - 3 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Recursivity - Problem
#7
Some observations:

- function can return three different datatypes: None, int and str. Whatever usage follows, it must be very defensive (None if empty list, int if list with one integer, string as expected result)

- for me personally it's more natural to return only one datatype. In case of empty list it should be empty string

- it works only when elements are strings, otherwise TypeError will be raised

It's of course upon specific needs but nevertheless I would have solved this problem differently. I would have separated flattening the list and manipulating list elements.

I would have created stream of elements of flattened list:

def flat_stream(lst):
    for item in lst:
        if isinstance(item, (list, tuple)):
            yield from flat_stream(item)
        else:
            yield item


This returns generator object which is memory efficient. It preserves all elements in their original type (which is often needed).

Now I can manipulate this stream whatever way I want:

>>> ls = ["a",["b","6"],"e",["5",["g","h"]],"i",["k"]]
>>> ''.join(el for el in flat_stream(ls))
'ab6e5ghik'
>>> list(flat_stream(ls))
['a', 'b', '6', 'e', '5', 'g', 'h', 'i', 'k']
If there are different types of elements and I want to manage them differently (data often needs verifying, cleansing etc) then I can do it:

>>> ls = ["a",("b","6"),"e",[5,["g","h"]],"i",["k"]]                 # there is int and tuple in list
>>> ''.join(str(el) for el in flat_stream(ls))                       # convert all elements to str
'ab6e5ghik'
>>> ''.join(el for el in flat_stream(ls) if isinstance(el, str))     # ignore int
'ab6eghik'
>>> [el for el in flat_stream(ls) if not isinstance(el, str)]        # ignore strings
[5]
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Messages In This Thread
Recursivity - Problem - by SupaFlamme - Jan-14-2019, 09:48 PM
RE: Recursivity - Problem - by nilamo - Jan-14-2019, 10:10 PM
RE: Recursivity - Problem - by micseydel - Jan-14-2019, 11:35 PM
RE: Recursivity - Problem - by scidam - Jan-15-2019, 12:33 AM
RE: Recursivity - Problem - by micseydel - Jan-15-2019, 12:57 AM
RE: Recursivity - Problem - by scidam - Jan-15-2019, 01:15 AM
RE: Recursivity - Problem - by perfringo - Jan-15-2019, 09:49 AM

Forum Jump:

User Panel Messages

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