Characters contain themselves?

Scott David Daniels scott.daniels at acm.org
Mon Apr 10 12:50:24 EDT 2006


WENDUM Denis 47.76.11 (agent) wrote:
>...  From the answers I've got it seems I'll have to check if I'm
> iterating on a string or on another kind of "list"....
>>>> import sys
>>>> sys.setrecursionlimit(10)
>>>> def f(List):
> ...       try: # assuming List supports iteration
> ...           new=[f(item) for item in List]
> ...       except:# if no iteration is possible
> ...           new=1
> ...       return new
>>>> f([1, [2,3]]) # f substitutes each non iterable item by 1 (silly 
>>>> butshows the problem)
> [1, [1, 1]]
>>>> f([1, [2.3, (5,6,7)]])
> [1, [1, [1, 1, 1]]]
>>>> f('bac')
> [[[[[[[[1]]]]]]], [[[[[[[1]]]]]]], [[[[[[[1]]]]]]]]
>>>> sys.setrecursionlimit(5)
>>>> f('bac')
> [[[1]], [[1]], [[1]]]
>>>> # each item in 'bac' is a character, 
> ie. a string of length one on wich one can iterate
> and so triggers an infinite descent of recursion.

I'd rewrite your 'f' as follows:
     def copier(List):
         try: # assuming List supports iteration
	    new = [f(item) for item in List]
         except TypeError: # Non-iterables get replaced
             return '?'
         except RuntimeError: # Recursion failures get shown
             return 'Recursion'
         return new

Note, even if you got your wish and somehow you couldn't have an issue
with characters in strings, you would have to deal with this:

    simple_list = [3.1415]
    container = [simple_list]
    simple_list.append(container)

Your function (and mine) assumes the argument is a DAG (Directed Acyclic
Graph), but there is no such guarantee about data structures in python.

--Scott David Daniels
scott.daniels at acm.org



More information about the Python-list mailing list