Skip to content

Instantly share code, notes, and snippets.

@xiaolzha
Forked from tiye/recursion_demo.py
Created May 1, 2012 07:42
Show Gist options
  • Save xiaolzha/2565995 to your computer and use it in GitHub Desktop.
Save xiaolzha/2565995 to your computer and use it in GitHub Desktop.
recursion of ESC
#change to Python 3.x and fixed a bug
import types
cursor = '\t'
def recur(arr, cursorList, result):
if arr == []:
return (result , cursorList)
head = arr[0]
if type(head) is list:
(r,c) = recur(head, [], [])
return recur(arr[1:], cursorList, result + [r]+ c )
else:
if head == cursor:
return recur(arr[1:], cursorList + [head], result)
else:
return recur(arr[1:], cursorList, result + [head])
def helper (arr):
(r,c) = recur (arr,[],[])
return r+c
if __name__ == "__main__":
arr = ['3', '555', ['4', '\t']]
print (helper(arr))
# output: ['3', '555', ['4'], '\t']
arr = ['35', '65', ['4', ['\t', '45', ['5']]]]
print (helper(arr))
# output: ['35', '65', ['4', ['45', ['5']], '\t']]
arr = ['35', '65', ['4', ['\t', '45', ['5']]], '24']
print (helper(arr))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment