Guest User

Acing the technical interview in Python

a guest
Mar 16th, 2017
644
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.66 KB | None | 0 0
  1.  
  2. class nil:
  3.   pass
  4.  
  5. def cons(x, y):
  6.   return lambda v: x if v else y
  7.  
  8. def nth(l, n):
  9.   if l is nil:
  10.     return None
  11.   elif n == 0:
  12.     return l(True)
  13.   else:
  14.     return nth(l(False), n-1)
  15.  
  16. def prn_list(l):
  17.   print("("),
  18.   def inner(l):
  19.     if l is nil:
  20.       print(")")
  21.     else:
  22.       print(l(True)),
  23.       if l(False) is not nil:
  24.         print(" "),
  25.       inner(l(False))
  26.   inner(l)
  27.  
  28. def reverse(l):
  29.   def inner(r, l):
  30.     if l is not nil:
  31.       return inner(cons(l(True),r),l(False))
  32.     else:
  33.       return r
  34.   return inner(nil,l)
  35.  
  36. if __name__ == "__main__":
  37.   l = cons(1,cons(2,cons(3,nil)))
  38.   prn_list(l)
  39.   prn_list(reverse(l))
Advertisement
Add Comment
Please, Sign In to add comment