0

I am sure that this is a simple syntax issue but I can not figure out why my generator is returning a reference instead of the value expected.

def flatten(val):
  print('--------', val, '----------')
  o = []
  for thing in val:
    # print(thing, type(thing))
    if isinstance(thing, int):
        o.append(thing)

    if isinstance(thing, list):
        o.append(i for i in thing if isinstance(i, int))

print(o)
return o

if __name__ == '__main__':
  # flatten([0, 1, 2])
  flatten([0, [1], 2])

prints: 
[0, <generator object flatten.<locals>.<genexpr> at 0x7fe1d113b150>, 2]
Eman
  • 83
  • 6

1 Answers1

1

The following is a little modified version of your code but reads much cleaner and easier to understand:

def flatten(val):
    print('--------', val, '----------')
    o = []

    for thing in val:
        print(thing, type(thing))

        if isinstance(thing, int):
            o.append(thing)

        if isinstance(thing, list):
            for a_thing in thing:
                if isinstance(a_thing, int):
                    o.append(a_thing)

    return o

if __name__ == '__main__':
    result = flatten([0, [1], 2])
    print result

[0, 1, 2]

Some suggestion: While this script may be OK for experimenting however you may eventually need recursion to solve such problems. Recursive functions are a kind of function that call itself to get a job done. A question to ask is: what if your input array contains [0, [1,2,3], [4]]? In such case your will need a nested loop to solve the problem. The problem becomes more complicated when your input looks like: [0, [1,2,[3, 4]], [5]]. In such cases recursive functions are used.

Here is how a recursive function could solve the problem:

def flatten(*args):
    number_list = []
    for item in args:
        if isinstance(item, int):
            number_list.append(item)
        else:
            number_list += flatten(*item)

    return number_list

if __name__ == '__main__':
    print flatten([0, [1, 2, [3, 4, 5]], 6])

[0, 1, 2, 3, 4, 5, 6]

Community
  • 1
  • 1
Ahsan
  • 3,845
  • 2
  • 36
  • 36