Functional programming in Python: returning none instead of correct value -
i wrote functional code in python , not understand why returns none instead of correct value code generates.
the purpose of script take line.split(',') csv , reassemble values inadvertently split '{value1,value2,value3}' 'value1,value2 ... valuen'.
def reassemble(list_name): def inner_iter(head, tail): if head[0][0] == '{': new_head = [head[0] + ',' + tail[0]] if tail[0][-1] == '}': return [new_head[0][1:-1]], tail[1:] else: inner_iter(new_head, tail[1:]) def outer_iter(corrected_list, head, tail): if tail == []: print corrected_list + head return corrected_list + head else: if head[0][0] == '{': head, tail = inner_iter(head, tail) outer_iter(corrected_list + head, [tail[0]], tail[1:]) else: outer_iter(corrected_list + head, [tail[0]], tail[1:]) return outer_iter([], [list_name[0]], list_name[1:])
below test:
x = ['x','y', '{a', 'b}', 'c'] print reassemble(x)
and odd result:
['x', 'y', 'a,b', 'c'] #from print inside "outer_iter" none #from print reassemble(x)
note: want keep code functional exercise.
you forgot return
in else
clause, @ outer_iter
.
in python, function not return specific value, returns none
.
[edit]
full source:
def reassemble(list_name): def inner_iter(head, tail): if head[0][0] == '{': new_head = [head[0] + ',' + tail[0]] if tail[0][-1] == '}': return [new_head[0][1:-1]], tail[1:] else: return inner_iter(new_head, tail[1:]) #before change, control reached here upon return #control might still reach here, in case 'if' condition not met #implicitly "return none" def outer_iter(corrected_list, head, tail): if tail == []: print corrected_list + head return corrected_list + head else: if head[0][0] == '{': head, tail = inner_iter(head, tail) return outer_iter(corrected_list + head, [tail[0]], tail[1:]) #before change, control reached here upon return else: return outer_iter(corrected_list + head, [tail[0]], tail[1:]) #before change, control reached here upon return #before change, control reached here upon return #implicitly "return none" return outer_iter([], [list_name[0]], list_name[1:])
test:
x = ['x','y', '{a', 'b}', 'c'] print reassemble(x)
output:
['x', 'y', 'a,b', 'c'] ['x', 'y', 'a,b', 'c']