def recursive_reduce(fn, iterable): """ fn : fn (callable) that takes an iterable iterable : some iterable of (possible) iterables returns : list of list of ... after applying fn to each nested iterable Applies fn to each iterable within iterable, reducing nested iterables """ if not is_callable(fn): raise Exception("Parameter fn is NOT callable") if not is_iterable(iterable): raise Exception("Parameter iterable is NOT iterable") """ The true power of recursion! """ def rec_red(potential_iterable): lst = [] for i in potential_iterable: if is_iterable(i): lst.append(rec_red(i)) else: lst.append(i) return fn(lst) return rec_red(iterable)
def fltn(potential_iterable): lst = [] for i in potential_iterable: if is_iterable(i): lst.extend(fltn(i)) else: lst.append(i) return lst
def rec_red(potential_iterable): lst = [] for i in potential_iterable: if is_iterable(i): lst.append(rec_red(i)) else: lst.append(i) return fn(lst)
def recursive_map(fn, iterable): """ fn : fn (callable) that takes a non-iterable iterable : some iterable of (possible) iterables returns : list of list of ... after applying fn to each nested iterable Applies fn to each iterable within iterable, recursing through all nested iterables """ if not is_callable(fn): raise Exception("Parameter fn is NOT callable") if not is_iterable(iterable): raise Exception("Parameter iterable is NOT iterable") """ The true power of recursion! """ def rec_map(potential_iterable): if is_iterable(potential_iterable): return map(rec_map, potential_iterable) return fn(potential_iterable) return map(rec_map, iterable)
def flatten(iterable): """ iterable : some iterable of (possible) iterables returns : list of list of ... after applying fn to each nested iterable Applies fn to each iterable within iterable, recursing through all nested iterables """ if not is_iterable(iterable): raise Exception("Parameter iterable is NOT iterable") """ The true power of recursion! """ def fltn(potential_iterable): lst = [] for i in potential_iterable: if is_iterable(i): lst.extend(fltn(i)) else: lst.append(i) return lst return fltn(iterable)
def r_print(level, iterble): if is_iterable(iterble): for i in iterble: r_print(level + 1, i) else: print(padding_str * level, str(iterble))
def rec_map(potential_iterable): if is_iterable(potential_iterable): return map(rec_map, potential_iterable) return fn(potential_iterable)